From 1dc144c8c1ba68155ecb82967523057093e9bf83 Mon Sep 17 00:00:00 2001 From: gwenn Date: Sat, 1 Aug 2015 08:09:59 +0200 Subject: [PATCH 01/39] Add test_execute_select. --- src/lib.rs | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index f98780b..cd83fe2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -580,7 +580,7 @@ impl<'conn> SqliteStatement<'conn> { /// Get all the column names in the result set of the prepared statement. pub fn column_names(&self) -> Vec<&str> { - let n = unsafe { ffi::sqlite3_column_count(self.stmt) }; + let n = self.column_count(); let mut cols = Vec::with_capacity(n as usize); for i in 0..n { let slice = unsafe { @@ -625,11 +625,13 @@ impl<'conn> SqliteStatement<'conn> { self.needs_reset = true; let r = ffi::sqlite3_step(self.stmt); - match r { - ffi::SQLITE_DONE => Ok(self.conn.changes()), - ffi::SQLITE_ROW => Err(SqliteError{ code: r, - message: "Unexpected row result - did you mean to call query?".to_string() }), - _ => Err(self.conn.decode_result(r).unwrap_err()), + if r == ffi::SQLITE_ROW || self.column_count() != 0 { + Err(SqliteError{ code: r, + message: "Unexpected row result - did you mean to call query?".to_string() }) + } else if r == ffi::SQLITE_DONE { + Ok(self.conn.changes()) + } else { + Err(self.conn.decode_result(r).unwrap_err()) } } } @@ -710,6 +712,10 @@ impl<'conn> SqliteStatement<'conn> { } } + fn column_count(&self) -> c_int { + unsafe { ffi::sqlite3_column_count(self.stmt) } + } + fn finalize_(&mut self) -> SqliteResult<()> { let r = unsafe { ffi::sqlite3_finalize(self.stmt) }; self.stmt = ptr::null_mut(); @@ -895,7 +901,7 @@ impl<'stmt> SqliteRow<'stmt> { message: "Cannot get values from a row after advancing to next row".to_string() }); } unsafe { - if idx < 0 || idx >= ffi::sqlite3_column_count(self.stmt.stmt) { + if idx < 0 || idx >= self.stmt.column_count() { return Err(SqliteError{ code: ffi::SQLITE_MISUSE, message: "Invalid column index".to_string() }); } @@ -993,6 +999,14 @@ mod test { assert_eq!(3i32, db.query_row("SELECT SUM(x) FROM foo", &[], |r| r.get(0)).unwrap()); } + #[test] + fn test_execute_select() { + let db = checked_memory_handle(); + let err = db.execute("SELECT 1 WHERE 1 < ?", &[&1i32]).unwrap_err(); + assert!(err.code == ffi::SQLITE_DONE); + assert!(err.message == "Unexpected row result - did you mean to call query?"); + } + #[test] fn test_prepare_column_names() { let db = checked_memory_handle(); From c31c68d5e3acb41106680c54a0757ae06187f65b Mon Sep 17 00:00:00 2001 From: gwenn Date: Sat, 1 Aug 2015 09:11:31 +0200 Subject: [PATCH 02/39] Only check column count when DONE. --- src/lib.rs | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index cd83fe2..9ef89c3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -625,13 +625,18 @@ impl<'conn> SqliteStatement<'conn> { self.needs_reset = true; let r = ffi::sqlite3_step(self.stmt); - if r == ffi::SQLITE_ROW || self.column_count() != 0 { - Err(SqliteError{ code: r, - message: "Unexpected row result - did you mean to call query?".to_string() }) - } else if r == ffi::SQLITE_DONE { - Ok(self.conn.changes()) - } else { - Err(self.conn.decode_result(r).unwrap_err()) + match r { + ffi::SQLITE_DONE => { + if self.column_count() != 0 { + Err(SqliteError{ code: ffi::SQLITE_MISUSE, + message: "Unexpected column count - did you mean to call query?".to_string() }) + } else { + Ok(self.conn.changes()) + } + }, + ffi::SQLITE_ROW => Err(SqliteError{ code: r, + message: "Unexpected row result - did you mean to call query?".to_string() }), + _ => Err(self.conn.decode_result(r).unwrap_err()), } } } @@ -1003,8 +1008,8 @@ mod test { fn test_execute_select() { let db = checked_memory_handle(); let err = db.execute("SELECT 1 WHERE 1 < ?", &[&1i32]).unwrap_err(); - assert!(err.code == ffi::SQLITE_DONE); - assert!(err.message == "Unexpected row result - did you mean to call query?"); + assert!(err.code == ffi::SQLITE_MISUSE); + assert!(err.message == "Unexpected column count - did you mean to call query?"); } #[test] From f91db1b3503a8186d08f797ae0a3e32f2d9129a9 Mon Sep 17 00:00:00 2001 From: gwenn Date: Sat, 1 Aug 2015 10:08:28 +0200 Subject: [PATCH 03/39] Cache column_count (I am not sure it's worth it) --- src/lib.rs | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 9ef89c3..0435cb3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -571,16 +571,18 @@ pub struct SqliteStatement<'conn> { conn: &'conn SqliteConnection, stmt: *mut ffi::sqlite3_stmt, needs_reset: bool, + column_count: c_int, } impl<'conn> SqliteStatement<'conn> { fn new(conn: &SqliteConnection, stmt: *mut ffi::sqlite3_stmt) -> SqliteStatement { - SqliteStatement{ conn: conn, stmt: stmt, needs_reset: false } + SqliteStatement{ conn: conn, stmt: stmt, needs_reset: false, + column_count: unsafe { ffi::sqlite3_column_count(stmt) }} } /// Get all the column names in the result set of the prepared statement. pub fn column_names(&self) -> Vec<&str> { - let n = self.column_count(); + let n = self.column_count; let mut cols = Vec::with_capacity(n as usize); for i in 0..n { let slice = unsafe { @@ -627,7 +629,7 @@ impl<'conn> SqliteStatement<'conn> { let r = ffi::sqlite3_step(self.stmt); match r { ffi::SQLITE_DONE => { - if self.column_count() != 0 { + if self.column_count != 0 { Err(SqliteError{ code: ffi::SQLITE_MISUSE, message: "Unexpected column count - did you mean to call query?".to_string() }) } else { @@ -717,10 +719,6 @@ impl<'conn> SqliteStatement<'conn> { } } - fn column_count(&self) -> c_int { - unsafe { ffi::sqlite3_column_count(self.stmt) } - } - fn finalize_(&mut self) -> SqliteResult<()> { let r = unsafe { ffi::sqlite3_finalize(self.stmt) }; self.stmt = ptr::null_mut(); @@ -906,7 +904,7 @@ impl<'stmt> SqliteRow<'stmt> { message: "Cannot get values from a row after advancing to next row".to_string() }); } unsafe { - if idx < 0 || idx >= self.stmt.column_count() { + if idx < 0 || idx >= self.stmt.column_count { return Err(SqliteError{ code: ffi::SQLITE_MISUSE, message: "Invalid column index".to_string() }); } From 4fa6d3c020734d442c26411564f66ffe03155cf4 Mon Sep 17 00:00:00 2001 From: gwenn Date: Sat, 1 Aug 2015 10:18:06 +0200 Subject: [PATCH 04/39] Reset as soon as possible. --- src/lib.rs | 18 ++++-------------- 1 file changed, 4 insertions(+), 14 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 0435cb3..ecab5f6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -613,20 +613,11 @@ impl<'conn> SqliteStatement<'conn> { /// } /// ``` pub fn execute(&mut self, params: &[&ToSql]) -> SqliteResult { - self.reset_if_needed(); - unsafe { - assert!(params.len() as c_int == ffi::sqlite3_bind_parameter_count(self.stmt), - "incorrect number of parameters to execute(): expected {}, got {}", - ffi::sqlite3_bind_parameter_count(self.stmt), - params.len()); + try!(self.bind_parameters(params)); - for (i, p) in params.iter().enumerate() { - try!(self.conn.decode_result(p.bind_parameter(self.stmt, (i + 1) as c_int))); - } - - self.needs_reset = true; let r = ffi::sqlite3_step(self.stmt); + ffi::sqlite3_reset(self.stmt); match r { ffi::SQLITE_DONE => { if self.column_count != 0 { @@ -669,11 +660,12 @@ impl<'conn> SqliteStatement<'conn> { try!(self.bind_parameters(params)); } + self.needs_reset = true; Ok(SqliteRows::new(self)) } /// Executes the prepared statement and maps a function over the resulting - /// rows. + /// rows. /// /// Unlike the iterator produced by `query`, the returned iterator does not expose the possibility /// for accessing stale rows. @@ -707,8 +699,6 @@ impl<'conn> SqliteStatement<'conn> { try!(self.conn.decode_result(p.bind_parameter(self.stmt, (i + 1) as c_int))); } - self.needs_reset = true; - Ok(()) } From 4a7e83f0af8a1e7fab3faa7e348dcd62216409e5 Mon Sep 17 00:00:00 2001 From: gwenn Date: Sat, 1 Aug 2015 17:21:41 +0200 Subject: [PATCH 05/39] Feature sqlite3_{log,trace,profile}. --- Cargo.toml | 1 + libsqlite3-sys/src/lib.rs | 2 + src/lib.rs | 4 +- src/trace_extension.rs | 98 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 104 insertions(+), 1 deletion(-) create mode 100644 src/trace_extension.rs diff --git a/Cargo.toml b/Cargo.toml index 5d05ed5..772b4cc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,6 +14,7 @@ name = "rusqlite" [features] load_extension = ["libsqlite3-sys/load_extension"] +trace_extension = [] [dependencies] time = "~0.1.0" diff --git a/libsqlite3-sys/src/lib.rs b/libsqlite3-sys/src/lib.rs index 5d37276..51f33c5 100644 --- a/libsqlite3-sys/src/lib.rs +++ b/libsqlite3-sys/src/lib.rs @@ -92,3 +92,5 @@ pub fn code_to_str(code: c_int) -> &'static str { _ => "Unknown error code", } } + +pub const SQLITE_CONFIG_LOG : c_int = 16; diff --git a/src/lib.rs b/src/lib.rs index f98780b..d96fdfd 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -50,6 +50,7 @@ //! } //! } //! ``` +#![cfg_attr(test, feature(duration))] extern crate libc; extern crate libsqlite3_sys as ffi; #[macro_use] extern crate bitflags; @@ -79,6 +80,7 @@ pub use transaction::{SqliteTransactionBehavior, pub mod types; mod transaction; #[cfg(feature = "load_extension")] mod load_extension_guard; +#[cfg(feature = "trace_extension")] pub mod trace_extension; /// A typedef of the result returned by many methods. pub type SqliteResult = Result; @@ -664,7 +666,7 @@ impl<'conn> SqliteStatement<'conn> { } /// Executes the prepared statement and maps a function over the resulting - /// rows. + /// rows. /// /// Unlike the iterator produced by `query`, the returned iterator does not expose the possibility /// for accessing stale rows. diff --git a/src/trace_extension.rs b/src/trace_extension.rs new file mode 100644 index 0000000..cde1d75 --- /dev/null +++ b/src/trace_extension.rs @@ -0,0 +1,98 @@ +use libc::{c_char, c_int, c_void}; +use std::ffi::CString; +use std::ptr; + +use super::ffi; +use {SqliteError, SqliteResult, SqliteConnection}; + +pub type LogCallback = + Option; + +/// Set up the error logging callback +/// +/// cf [The Error And Warning Log](http://sqlite.org/errlog.html). +pub fn config_log(cb: LogCallback) -> SqliteResult<()> { + let rc = unsafe { + let p_arg: *mut c_void = ptr::null_mut(); + ffi::sqlite3_config(ffi::SQLITE_CONFIG_LOG, cb, p_arg) + }; + if rc != ffi::SQLITE_OK { + return Err(SqliteError{ code: rc, message: "sqlite3_config(SQLITE_CONFIG_LOG, ...)".to_string() }); + } + Ok(()) +} + +/// Write a message into the error log established by `config_log`. +pub fn log(err_code: c_int, msg: &str) { + let msg = CString::new(msg).unwrap(); + unsafe { + ffi::sqlite3_log(err_code, msg.as_ptr()); + } +} + +pub type TraceCallback = + Option; +pub type ProfileCallback = + Option; +impl SqliteConnection { + /// Register or clear a callback function that can be used for tracing the execution of SQL statements. + /// Prepared statement placeholders are replaced/logged with their assigned values. + /// There can only be a single tracer defined for each database connection. + /// Setting a new tracer clears the old one. + pub fn trace(&mut self, x_trace: TraceCallback) { + let c = self.db.borrow_mut(); + unsafe { ffi::sqlite3_trace(c.db(), x_trace, ptr::null_mut()); } + } + /// Register or clear a callback function that can be used for profiling the execution of SQL statements. + /// There can only be a single profiler defined for each database connection. + /// Setting a new profiler clears the old one. + pub fn profile(&mut self, x_profile: ProfileCallback) { + let c = self.db.borrow_mut(); + unsafe { ffi::sqlite3_profile(c.db(), x_profile, ptr::null_mut()); } + } +} + +#[cfg(test)] +mod test { + use libc::{c_char, c_int, c_void}; + use std::ffi::CStr; + use std::io::Write; + use std::str; + + use ffi; + use SqliteConnection; + + extern "C" fn log_callback(_: *mut c_void, err: c_int, msg: *const c_char) { + unsafe { + let c_slice = CStr::from_ptr(msg).to_bytes(); + let _ = writeln!(::std::io::stderr(), "{}: {:?}", err, str::from_utf8(c_slice)); + } + } + + #[test] + fn test_log() { + if true { // To avoid freezing tests + return + } + unsafe { ffi::sqlite3_shutdown() }; + super::config_log(Some(log_callback)).unwrap(); + //super::log(ffi::SQLITE_NOTICE, "message from rusqlite"); + super::config_log(None).unwrap(); + } + + extern "C" fn profile_callback(_: *mut ::libc::c_void, sql: *const ::libc::c_char, nanoseconds: u64) { + use std::time::Duration; + unsafe { + let c_slice = ::std::ffi::CStr::from_ptr(sql).to_bytes(); + let d = Duration::from_millis(nanoseconds / 1_000_000); + let _ = writeln!(::std::io::stderr(), "PROFILE: {:?} ({})", ::std::str::from_utf8(c_slice), d); + } + } + + #[test] + fn test_profile() { + let mut db = SqliteConnection::open_in_memory().unwrap(); + db.profile(Some(profile_callback)); + db.execute_batch("PRAGMA application_id = 1").unwrap(); + } +} \ No newline at end of file From ef254fdca00d2fbf79830e0f1abb3e6dcef9f702 Mon Sep 17 00:00:00 2001 From: gwenn Date: Sat, 1 Aug 2015 18:58:04 +0200 Subject: [PATCH 06/39] Rename feature to 'trace' --- Cargo.toml | 2 +- src/lib.rs | 2 +- src/{trace_extension.rs => trace.rs} | 0 3 files changed, 2 insertions(+), 2 deletions(-) rename src/{trace_extension.rs => trace.rs} (100%) diff --git a/Cargo.toml b/Cargo.toml index 772b4cc..777d50c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,7 +14,7 @@ name = "rusqlite" [features] load_extension = ["libsqlite3-sys/load_extension"] -trace_extension = [] +trace = [] [dependencies] time = "~0.1.0" diff --git a/src/lib.rs b/src/lib.rs index d96fdfd..3c03fef 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -80,7 +80,7 @@ pub use transaction::{SqliteTransactionBehavior, pub mod types; mod transaction; #[cfg(feature = "load_extension")] mod load_extension_guard; -#[cfg(feature = "trace_extension")] pub mod trace_extension; +#[cfg(feature = "trace")] pub mod trace; /// A typedef of the result returned by many methods. pub type SqliteResult = Result; diff --git a/src/trace_extension.rs b/src/trace.rs similarity index 100% rename from src/trace_extension.rs rename to src/trace.rs From 9c415f9c9e433101564767603e0be7aa341c7343 Mon Sep 17 00:00:00 2001 From: Gwenael Treguier Date: Sun, 2 Aug 2015 12:16:01 +0200 Subject: [PATCH 07/39] Remove usage of unstable library feature 'duration' --- src/lib.rs | 1 - src/trace.rs | 10 ++++------ 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 3c03fef..4dfd068 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -50,7 +50,6 @@ //! } //! } //! ``` -#![cfg_attr(test, feature(duration))] extern crate libc; extern crate libsqlite3_sys as ffi; #[macro_use] extern crate bitflags; diff --git a/src/trace.rs b/src/trace.rs index cde1d75..de03742 100644 --- a/src/trace.rs +++ b/src/trace.rs @@ -80,19 +80,17 @@ mod test { super::config_log(None).unwrap(); } - extern "C" fn profile_callback(_: *mut ::libc::c_void, sql: *const ::libc::c_char, nanoseconds: u64) { - use std::time::Duration; + extern "C" fn trace_callback(_: *mut ::libc::c_void, sql: *const ::libc::c_char) { unsafe { let c_slice = ::std::ffi::CStr::from_ptr(sql).to_bytes(); - let d = Duration::from_millis(nanoseconds / 1_000_000); - let _ = writeln!(::std::io::stderr(), "PROFILE: {:?} ({})", ::std::str::from_utf8(c_slice), d); + let _ = writeln!(::std::io::stderr(), "TRACE: {:?}", ::std::str::from_utf8(c_slice)); } } #[test] - fn test_profile() { + fn test_trace() { let mut db = SqliteConnection::open_in_memory().unwrap(); - db.profile(Some(profile_callback)); + db.trace(Some(trace_callback)); db.execute_batch("PRAGMA application_id = 1").unwrap(); } } \ No newline at end of file From 7b8051dc7ea087d3346ba71fcfc10a62310fe39a Mon Sep 17 00:00:00 2001 From: Gwenael Treguier Date: Thu, 6 Aug 2015 21:15:30 +0200 Subject: [PATCH 08/39] Check Rust str length before binding. --- src/types.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/types.rs b/src/types.rs index 1d30b30..f55a80e 100644 --- a/src/types.rs +++ b/src/types.rs @@ -102,8 +102,12 @@ raw_to_impl!(c_double, sqlite3_bind_double); impl<'a> ToSql for &'a str { unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int { + let length = self.len(); + if length > ::std::i32::MAX as usize { + return ffi::SQLITE_TOOBIG; + } match str_to_cstring(self) { - Ok(c_str) => ffi::sqlite3_bind_text(stmt, col, c_str.as_ptr(), -1, + Ok(c_str) => ffi::sqlite3_bind_text(stmt, col, c_str.as_ptr(), length as c_int, ffi::SQLITE_TRANSIENT()), Err(_) => ffi::SQLITE_MISUSE, } From 9c63b9f37a24117c022129b0f37736938df5e563 Mon Sep 17 00:00:00 2001 From: Gwenael Treguier Date: Thu, 6 Aug 2015 21:45:54 +0200 Subject: [PATCH 09/39] Check Rust blob length before binding. --- src/types.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/types.rs b/src/types.rs index f55a80e..5ad4ed7 100644 --- a/src/types.rs +++ b/src/types.rs @@ -122,6 +122,9 @@ impl ToSql for String { impl<'a> ToSql for &'a [u8] { unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int { + if self.len() > ::std::i32::MAX as usize { + return ffi::SQLITE_TOOBIG; + } ffi::sqlite3_bind_blob( stmt, col, mem::transmute(self.as_ptr()), self.len() as c_int, ffi::SQLITE_TRANSIENT()) } From 6bc1a8bb59fd22d07646495b0426703e755a9785 Mon Sep 17 00:00:00 2001 From: Gwenael Treguier Date: Sat, 8 Aug 2015 09:30:50 +0200 Subject: [PATCH 10/39] Check when statement is too long. --- src/lib.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index f98780b..c49da64 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -542,6 +542,12 @@ impl InnerSqliteConnection { fn prepare<'a>(&mut self, conn: &'a SqliteConnection, sql: &str) -> SqliteResult> { + if sql.len() >= ::std::i32::MAX as usize { + return Err(SqliteError { + code: ffi::SQLITE_TOOBIG, + message: "statement too long".to_string() + }); + } let mut c_stmt: *mut ffi::sqlite3_stmt = unsafe { mem::uninitialized() }; let c_sql = try!(str_to_cstring(sql)); let r = unsafe { From 59a4c5593a92c61058bff40ed64edd2a07f5423f Mon Sep 17 00:00:00 2001 From: Gwenael Treguier Date: Sat, 8 Aug 2015 09:57:07 +0200 Subject: [PATCH 11/39] Improve documentation. --- src/trace.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/trace.rs b/src/trace.rs index de03742..b3c9939 100644 --- a/src/trace.rs +++ b/src/trace.rs @@ -1,3 +1,4 @@ +//! Tracing and profiling functions. Error and warning log. use libc::{c_char, c_int, c_void}; use std::ffi::CString; use std::ptr; @@ -30,12 +31,16 @@ pub fn log(err_code: c_int, msg: &str) { } } +/// The trace callback function signature. pub type TraceCallback = Option; +/// The profile callback function signature. pub type ProfileCallback = Option; + impl SqliteConnection { /// Register or clear a callback function that can be used for tracing the execution of SQL statements. + /// /// Prepared statement placeholders are replaced/logged with their assigned values. /// There can only be a single tracer defined for each database connection. /// Setting a new tracer clears the old one. @@ -44,6 +49,7 @@ impl SqliteConnection { unsafe { ffi::sqlite3_trace(c.db(), x_trace, ptr::null_mut()); } } /// Register or clear a callback function that can be used for profiling the execution of SQL statements. + /// /// There can only be a single profiler defined for each database connection. /// Setting a new profiler clears the old one. pub fn profile(&mut self, x_profile: ProfileCallback) { From e1532f5edfeec447de44465494df739f23e5e6a8 Mon Sep 17 00:00:00 2001 From: Patrick Fernie Date: Thu, 27 Aug 2015 10:44:24 -0400 Subject: [PATCH 12/39] Correct idx-checking behavior for SqliteRow::get_checked() --- src/lib.rs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index f98780b..290c4a2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -866,9 +866,19 @@ impl<'stmt> SqliteRow<'stmt> { /// Returns a `SQLITE_MISMATCH`-coded `SqliteError` if the underlying SQLite column /// type is not a valid type as a source for `T`. /// - /// Panics if `idx` is outside the range of columns in the returned query or if this row - /// is stale. + /// Returns a `SQLITE_MISUSE`-coded `SqliteError` if `idx` is outside the valid column range + /// for this row or if this row is stale. pub fn get_checked(&self, idx: c_int) -> SqliteResult { + if self.row_idx != self.current_row.get() { + return Err(SqliteError{ code: ffi::SQLITE_MISUSE, + message: "Cannot get values from a row after advancing to next row".to_string() }); + } + unsafe { + if idx < 0 || idx >= ffi::sqlite3_column_count(self.stmt.stmt) { + return Err(SqliteError{ code: ffi::SQLITE_MISUSE, + message: "Invalid column index".to_string() }); + } + } let valid_column_type = unsafe { T::column_has_valid_sqlite_type(self.stmt.stmt, idx) }; From 29072e585b289426bd248fb6ddc523adad8dc833 Mon Sep 17 00:00:00 2001 From: Patrick Fernie Date: Thu, 27 Aug 2015 13:43:43 -0400 Subject: [PATCH 13/39] Implement SqliteStatement::query_and_then() Allows for more ergonomic unification of error types --- src/lib.rs | 226 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 224 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 290c4a2..229cc8e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -55,6 +55,7 @@ extern crate libsqlite3_sys as ffi; #[macro_use] extern crate bitflags; use std::default::Default; +use std::convert; use std::mem; use std::ptr; use std::fmt; @@ -90,7 +91,7 @@ unsafe fn errmsg_to_string(errmsg: *const c_char) -> String { } /// Encompasses an error result from a call to the SQLite C API. -#[derive(Debug)] +#[derive(Debug, PartialEq)] pub struct SqliteError { /// The error code returned by a SQLite C API call. See [SQLite Result /// Codes](http://www.sqlite.org/rescode.html) for details. @@ -664,7 +665,7 @@ impl<'conn> SqliteStatement<'conn> { } /// Executes the prepared statement and maps a function over the resulting - /// rows. + /// rows. /// /// Unlike the iterator produced by `query`, the returned iterator does not expose the possibility /// for accessing stale rows. @@ -680,6 +681,25 @@ impl<'conn> SqliteStatement<'conn> { }) } + /// Executes the prepared statement and maps a function over the resulting + /// rows, where the function returns a `Result` with `Error` type implementing + /// `std::convert::From` (so errors can be unified). + /// + /// Unlike the iterator produced by `query`, the returned iterator does not expose the possibility + /// for accessing stale rows. + pub fn query_and_then<'a, T, E, F>(&'a mut self, params: &[&ToSql], f: F) + -> SqliteResult> + where T: 'static, + E: convert::From, + F: FnMut(SqliteRow) -> Result { + let row_iter = try!(self.query(params)); + + Ok(AndThenRows{ + rows: row_iter, + map: f, + }) + } + /// Consumes the statement. /// /// Functionally equivalent to the `Drop` implementation, but allows callers to see any errors @@ -746,6 +766,28 @@ impl<'stmt, T, F> Iterator for MappedRows<'stmt, F> } } +/// An iterator over the mapped resulting rows of a query, with an Error type +/// unifying with SqliteError. +pub struct AndThenRows<'stmt, F> { + rows: SqliteRows<'stmt>, + map: F, +} + +impl<'stmt, T, E, F> Iterator for AndThenRows<'stmt, F> + where T: 'static, + E: convert::From, + F: FnMut(SqliteRow) -> Result { + type Item = Result; + + // Through the magic of FromIterator, if F returns a Result, + // you can collect that to a Result, E> + fn next(&mut self) -> Option { + self.rows.next().map(|row_result| row_result + .map_err(E::from) + .and_then(|row| (self.map)(row))) + } +} + /// An iterator over the resulting rows of a query. /// /// ## Warning @@ -920,6 +962,8 @@ mod test { extern crate tempdir; use super::*; use self::tempdir::TempDir; + use std::error::Error as StdError; + use std::fmt; // this function is never called, but is still type checked; in // particular, calls with specific instantiations will require @@ -1081,6 +1125,184 @@ mod test { assert_eq!(results.unwrap().concat(), "hello, world!"); } + #[test] + fn test_query_and_then() { + let db = checked_memory_handle(); + let sql = "BEGIN; + CREATE TABLE foo(x INTEGER, y TEXT); + INSERT INTO foo VALUES(4, \"hello\"); + INSERT INTO foo VALUES(3, \", \"); + INSERT INTO foo VALUES(2, \"world\"); + INSERT INTO foo VALUES(1, \"!\"); + END;"; + db.execute_batch(sql).unwrap(); + + let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap(); + let results: SqliteResult> = query + .query_and_then(&[], |row| row.get_checked(1)) + .unwrap() + .collect(); + + assert_eq!(results.unwrap().concat(), "hello, world!"); + } + + #[test] + fn test_query_and_then_fails() { + let db = checked_memory_handle(); + let sql = "BEGIN; + CREATE TABLE foo(x INTEGER, y TEXT); + INSERT INTO foo VALUES(4, \"hello\"); + INSERT INTO foo VALUES(3, \", \"); + INSERT INTO foo VALUES(2, \"world\"); + INSERT INTO foo VALUES(1, \"!\"); + END;"; + db.execute_batch(sql).unwrap(); + + let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap(); + let bad_type: SqliteResult> = query + .query_and_then(&[], |row| row.get_checked(1)) + .unwrap() + .collect(); + + assert_eq!(bad_type, Err(SqliteError{ + code: ffi::SQLITE_MISMATCH, + message: "Invalid column type".to_owned(), + })); + + let bad_idx: SqliteResult> = query + .query_and_then(&[], |row| row.get_checked(3)) + .unwrap() + .collect(); + + assert_eq!(bad_idx, Err(SqliteError{ + code: ffi::SQLITE_MISUSE, + message: "Invalid column index".to_owned(), + })); + } + + #[test] + fn test_query_and_then_custom_error() { + #[derive(Debug)] + enum CustomError { + Sqlite(SqliteError), + }; + + impl fmt::Display for CustomError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + CustomError::Sqlite(ref se) => write!(f, "{}: {}", self.description(), se), + } + } + } + + impl StdError for CustomError { + fn description(&self) -> &str { "my custom error" } + fn cause(&self) -> Option<&StdError> { + match *self { + CustomError::Sqlite(ref se) => Some(se), + } + } + } + + impl From for CustomError { + fn from(se: SqliteError) -> CustomError { + CustomError::Sqlite(se) + } + } + type CustomResult = Result; + + let db = checked_memory_handle(); + let sql = "BEGIN; + CREATE TABLE foo(x INTEGER, y TEXT); + INSERT INTO foo VALUES(4, \"hello\"); + INSERT INTO foo VALUES(3, \", \"); + INSERT INTO foo VALUES(2, \"world\"); + INSERT INTO foo VALUES(1, \"!\"); + END;"; + db.execute_batch(sql).unwrap(); + + let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap(); + let results: CustomResult> = query + .query_and_then(&[], |row| row.get_checked(1).map_err(CustomError::Sqlite)) + .unwrap() + .collect(); + + assert_eq!(results.unwrap().concat(), "hello, world!"); + } + + #[test] + fn test_query_and_then_custom_error_fails() { + #[derive(Debug, PartialEq)] + enum CustomError { + SomeError, + Sqlite(SqliteError), + }; + + impl fmt::Display for CustomError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + CustomError::SomeError => write!(f, "{}", self.description()), + CustomError::Sqlite(ref se) => write!(f, "{}: {}", self.description(), se), + } + } + } + + impl StdError for CustomError { + fn description(&self) -> &str { "my custom error" } + fn cause(&self) -> Option<&StdError> { + match *self { + CustomError::SomeError => None, + CustomError::Sqlite(ref se) => Some(se), + } + } + } + + impl From for CustomError { + fn from(se: SqliteError) -> CustomError { + CustomError::Sqlite(se) + } + } + type CustomResult = Result; + + let db = checked_memory_handle(); + let sql = "BEGIN; + CREATE TABLE foo(x INTEGER, y TEXT); + INSERT INTO foo VALUES(4, \"hello\"); + INSERT INTO foo VALUES(3, \", \"); + INSERT INTO foo VALUES(2, \"world\"); + INSERT INTO foo VALUES(1, \"!\"); + END;"; + db.execute_batch(sql).unwrap(); + + let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap(); + let bad_type: CustomResult> = query + .query_and_then(&[], |row| row.get_checked(1).map_err(CustomError::Sqlite)) + .unwrap() + .collect(); + + assert_eq!(bad_type, Err(CustomError::Sqlite(SqliteError{ + code: ffi::SQLITE_MISMATCH, + message: "Invalid column type".to_owned(), + }))); + + let bad_idx: CustomResult> = query + .query_and_then(&[], |row| row.get_checked(3).map_err(CustomError::Sqlite)) + .unwrap() + .collect(); + + assert_eq!(bad_idx, Err(CustomError::Sqlite(SqliteError{ + code: ffi::SQLITE_MISUSE, + message: "Invalid column index".to_owned(), + }))); + + let non_sqlite_err: CustomResult> = query + .query_and_then(&[], |_| Err(CustomError::SomeError)) + .unwrap() + .collect(); + + assert_eq!(non_sqlite_err, Err(CustomError::SomeError)); + } + #[test] fn test_query_row() { let db = checked_memory_handle(); From e4eda2041e804f38922952cac1ee2e1e974e191b Mon Sep 17 00:00:00 2001 From: Patrick Fernie Date: Thu, 27 Aug 2015 14:01:01 -0400 Subject: [PATCH 14/39] Implement SqliteConnection::query_row_and_then() --- src/lib.rs | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 229cc8e..91f32db 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -302,6 +302,37 @@ impl SqliteConnection { } } + /// Convenience method to execute a query that is expected to return a single row, + /// and execute a mapping via `f` on that returned row with the possibility of failure. + /// The `Result` type of `f` must implement `std::convert::From`. + /// + /// ## Example + /// + /// ```rust,no_run + /// # use rusqlite::{SqliteResult,SqliteConnection}; + /// fn preferred_locale(conn: &SqliteConnection) -> SqliteResult { + /// conn.query_row_and_then("SELECT value FROM preferences WHERE name='locale'", &[], |row| { + /// row.get_checked(0) + /// }) + /// } + /// ``` + /// + /// If the query returns more than one row, all rows except the first are ignored. + pub fn query_row_and_then(&self, sql: &str, params: &[&ToSql], f: F) -> Result + where F: FnOnce(SqliteRow) -> Result, + E: convert::From { + let mut stmt = try!(self.prepare(sql)); + let mut rows = try!(stmt.query(params)); + + match rows.next() { + Some(row) => row.map_err(E::from).and_then(f), + None => Err(E::from(SqliteError{ + code: ffi::SQLITE_NOTICE, + message: "Query did not return a row".to_string(), + })) + } + } + /// Convenience method to execute a query that is expected to return a single row. /// /// ## Example @@ -779,8 +810,6 @@ impl<'stmt, T, E, F> Iterator for AndThenRows<'stmt, F> F: FnMut(SqliteRow) -> Result { type Item = Result; - // Through the magic of FromIterator, if F returns a Result, - // you can collect that to a Result, E> fn next(&mut self) -> Option { self.rows.next().map(|row_result| row_result .map_err(E::from) From b7efb37b3542522247a6a9da037889cd3d947cfc Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Tue, 8 Sep 2015 18:06:41 +1000 Subject: [PATCH 15/39] Relax uses of `P: AsRef<...>` from `&P` to `P`. This means that one can pass `AsRef` types directly, without having to insert a `&`, e.g. `SqliteConnection::open("foo.db")` (new) vs. `SqliteConnection::open(&"foo.db")` (old). This should be backwards compatible, since there is an impl in the standard library: impl<'a, T, U> AsRef for &'a T where U: ?Sized, T: AsRef + ?Sized I.e. the old `&P` satisfies the new bound still. (Taking `P` directly is what the standard library does with similar functions, like `File::open`.) --- src/lib.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index f98780b..0814ecb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -160,7 +160,7 @@ impl SqliteConnection { /// /// `SqliteConnection::open(path)` is equivalent to `SqliteConnection::open_with_flags(path, /// SQLITE_OPEN_READ_WRITE | SQLITE_OPEN_CREATE)`. - pub fn open>(path: &P) -> SqliteResult { + pub fn open>(path: P) -> SqliteResult { let flags = Default::default(); SqliteConnection::open_with_flags(path, flags) } @@ -175,7 +175,7 @@ impl SqliteConnection { /// /// Database Connection](http://www.sqlite.org/c3ref/open.html) for a description of valid /// flag combinations. - pub fn open_with_flags>(path: &P, flags: SqliteOpenFlags) + pub fn open_with_flags>(path: P, flags: SqliteOpenFlags) -> SqliteResult { let c_path = try!(path_to_cstring(path.as_ref())); InnerSqliteConnection::open_with_flags(&c_path, flags).map(|db| { @@ -393,10 +393,10 @@ impl SqliteConnection { /// fn load_my_extension(conn: &SqliteConnection) -> SqliteResult<()> { /// let _guard = try!(SqliteLoadExtensionGuard::new(conn)); /// - /// conn.load_extension(Path::new("my_sqlite_extension"), None) + /// conn.load_extension("my_sqlite_extension", None) /// } #[cfg(feature = "load_extension")] - pub fn load_extension>(&self, dylib_path: &P, entry_point: Option<&str>) -> SqliteResult<()> { + pub fn load_extension>(&self, dylib_path: P, entry_point: Option<&str>) -> SqliteResult<()> { self.db.borrow_mut().load_extension(dylib_path, entry_point) } From 05669082a343ad08166968336810cc72bf51941a Mon Sep 17 00:00:00 2001 From: gwenn Date: Sat, 1 Aug 2015 12:04:02 +0200 Subject: [PATCH 16/39] Debug db path and stmt sql. --- src/lib.rs | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 530cfc0..eb96b11 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -58,7 +58,7 @@ use std::default::Default; use std::mem; use std::ptr; use std::fmt; -use std::path::{Path}; +use std::path::{Path,PathBuf}; use std::error; use std::rc::{Rc}; use std::cell::{RefCell, Cell}; @@ -151,6 +151,7 @@ fn path_to_cstring(p: &Path) -> SqliteResult { /// prepare multiple statements at the same time). pub struct SqliteConnection { db: RefCell, + path: Option, } unsafe impl Send for SqliteConnection {} @@ -179,7 +180,7 @@ impl SqliteConnection { -> SqliteResult { let c_path = try!(path_to_cstring(path.as_ref())); InnerSqliteConnection::open_with_flags(&c_path, flags).map(|db| { - SqliteConnection{ db: RefCell::new(db) } + SqliteConnection{ db: RefCell::new(db), path: Some(path.as_ref().to_path_buf()) } }) } @@ -190,7 +191,7 @@ impl SqliteConnection { pub fn open_in_memory_with_flags(flags: SqliteOpenFlags) -> SqliteResult { let c_memory = try!(str_to_cstring(":memory:")); InnerSqliteConnection::open_with_flags(&c_memory, flags).map(|db| { - SqliteConnection{ db: RefCell::new(db) } + SqliteConnection{ db: RefCell::new(db), path: None } }) } @@ -411,7 +412,7 @@ impl SqliteConnection { impl fmt::Debug for SqliteConnection { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "SqliteConnection()") + write!(f, "SqliteConnection( path: {:?} )", &self.path) } } @@ -673,7 +674,7 @@ impl<'conn> SqliteStatement<'conn> { } /// Executes the prepared statement and maps a function over the resulting - /// rows. + /// rows. /// /// Unlike the iterator produced by `query`, the returned iterator does not expose the possibility /// for accessing stale rows. @@ -728,7 +729,11 @@ impl<'conn> SqliteStatement<'conn> { impl<'conn> fmt::Debug for SqliteStatement<'conn> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Statement( conn: {:?}, stmt: {:?} )", self.conn, self.stmt) + let sql = unsafe { + let c_slice = CStr::from_ptr(ffi::sqlite3_sql(self.stmt)).to_bytes(); + str::from_utf8(c_slice) + }; + write!(f, "SqliteStatement( conn: {:?}, stmt: {:?}, sql: {:?} )", self.conn, self.stmt, sql) } } From d07c7ec8a6b9bb2935b0b464aef7137b582a782b Mon Sep 17 00:00:00 2001 From: John Gallagher Date: Sun, 20 Sep 2015 20:44:51 -0400 Subject: [PATCH 17/39] Add basic unit test of statement debug including SQL --- src/lib.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index eb96b11..622fb09 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1161,4 +1161,13 @@ mod test { } assert_eq!(db.last_insert_rowid(), 10); } + + #[test] + fn test_statement_debugging() { + let db = checked_memory_handle(); + let query = "SELECT 12345"; + let stmt = db.prepare(query).unwrap(); + + assert!(format!("{:?}", stmt).contains(query)); + } } From 072a336b33d42ec8726e820359e6d9342ada50bb Mon Sep 17 00:00:00 2001 From: John Gallagher Date: Sun, 20 Sep 2015 21:28:50 -0400 Subject: [PATCH 18/39] Refactor: Reduce duplication across query_and_then tests. --- src/lib.rs | 342 +++++++++++++++++++++++++---------------------------- 1 file changed, 160 insertions(+), 182 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index cd381b2..c142a1c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1003,10 +1003,10 @@ impl<'stmt> SqliteRow<'stmt> { mod test { extern crate libsqlite3_sys as ffi; extern crate tempdir; - use super::*; + pub use super::*; use self::tempdir::TempDir; - use std::error::Error as StdError; - use std::fmt; + pub use std::error::Error as StdError; + pub use std::fmt; // this function is never called, but is still type checked; in // particular, calls with specific instantiations will require @@ -1016,7 +1016,7 @@ mod test { ensure_send::(); } - fn checked_memory_handle() -> SqliteConnection { + pub fn checked_memory_handle() -> SqliteConnection { SqliteConnection::open_in_memory().unwrap() } @@ -1176,184 +1176,6 @@ mod test { assert_eq!(results.unwrap().concat(), "hello, world!"); } - #[test] - fn test_query_and_then() { - let db = checked_memory_handle(); - let sql = "BEGIN; - CREATE TABLE foo(x INTEGER, y TEXT); - INSERT INTO foo VALUES(4, \"hello\"); - INSERT INTO foo VALUES(3, \", \"); - INSERT INTO foo VALUES(2, \"world\"); - INSERT INTO foo VALUES(1, \"!\"); - END;"; - db.execute_batch(sql).unwrap(); - - let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap(); - let results: SqliteResult> = query - .query_and_then(&[], |row| row.get_checked(1)) - .unwrap() - .collect(); - - assert_eq!(results.unwrap().concat(), "hello, world!"); - } - - #[test] - fn test_query_and_then_fails() { - let db = checked_memory_handle(); - let sql = "BEGIN; - CREATE TABLE foo(x INTEGER, y TEXT); - INSERT INTO foo VALUES(4, \"hello\"); - INSERT INTO foo VALUES(3, \", \"); - INSERT INTO foo VALUES(2, \"world\"); - INSERT INTO foo VALUES(1, \"!\"); - END;"; - db.execute_batch(sql).unwrap(); - - let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap(); - let bad_type: SqliteResult> = query - .query_and_then(&[], |row| row.get_checked(1)) - .unwrap() - .collect(); - - assert_eq!(bad_type, Err(SqliteError{ - code: ffi::SQLITE_MISMATCH, - message: "Invalid column type".to_owned(), - })); - - let bad_idx: SqliteResult> = query - .query_and_then(&[], |row| row.get_checked(3)) - .unwrap() - .collect(); - - assert_eq!(bad_idx, Err(SqliteError{ - code: ffi::SQLITE_MISUSE, - message: "Invalid column index".to_owned(), - })); - } - - #[test] - fn test_query_and_then_custom_error() { - #[derive(Debug)] - enum CustomError { - Sqlite(SqliteError), - }; - - impl fmt::Display for CustomError { - fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { - match *self { - CustomError::Sqlite(ref se) => write!(f, "{}: {}", self.description(), se), - } - } - } - - impl StdError for CustomError { - fn description(&self) -> &str { "my custom error" } - fn cause(&self) -> Option<&StdError> { - match *self { - CustomError::Sqlite(ref se) => Some(se), - } - } - } - - impl From for CustomError { - fn from(se: SqliteError) -> CustomError { - CustomError::Sqlite(se) - } - } - type CustomResult = Result; - - let db = checked_memory_handle(); - let sql = "BEGIN; - CREATE TABLE foo(x INTEGER, y TEXT); - INSERT INTO foo VALUES(4, \"hello\"); - INSERT INTO foo VALUES(3, \", \"); - INSERT INTO foo VALUES(2, \"world\"); - INSERT INTO foo VALUES(1, \"!\"); - END;"; - db.execute_batch(sql).unwrap(); - - let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap(); - let results: CustomResult> = query - .query_and_then(&[], |row| row.get_checked(1).map_err(CustomError::Sqlite)) - .unwrap() - .collect(); - - assert_eq!(results.unwrap().concat(), "hello, world!"); - } - - #[test] - fn test_query_and_then_custom_error_fails() { - #[derive(Debug, PartialEq)] - enum CustomError { - SomeError, - Sqlite(SqliteError), - }; - - impl fmt::Display for CustomError { - fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { - match *self { - CustomError::SomeError => write!(f, "{}", self.description()), - CustomError::Sqlite(ref se) => write!(f, "{}: {}", self.description(), se), - } - } - } - - impl StdError for CustomError { - fn description(&self) -> &str { "my custom error" } - fn cause(&self) -> Option<&StdError> { - match *self { - CustomError::SomeError => None, - CustomError::Sqlite(ref se) => Some(se), - } - } - } - - impl From for CustomError { - fn from(se: SqliteError) -> CustomError { - CustomError::Sqlite(se) - } - } - type CustomResult = Result; - - let db = checked_memory_handle(); - let sql = "BEGIN; - CREATE TABLE foo(x INTEGER, y TEXT); - INSERT INTO foo VALUES(4, \"hello\"); - INSERT INTO foo VALUES(3, \", \"); - INSERT INTO foo VALUES(2, \"world\"); - INSERT INTO foo VALUES(1, \"!\"); - END;"; - db.execute_batch(sql).unwrap(); - - let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap(); - let bad_type: CustomResult> = query - .query_and_then(&[], |row| row.get_checked(1).map_err(CustomError::Sqlite)) - .unwrap() - .collect(); - - assert_eq!(bad_type, Err(CustomError::Sqlite(SqliteError{ - code: ffi::SQLITE_MISMATCH, - message: "Invalid column type".to_owned(), - }))); - - let bad_idx: CustomResult> = query - .query_and_then(&[], |row| row.get_checked(3).map_err(CustomError::Sqlite)) - .unwrap() - .collect(); - - assert_eq!(bad_idx, Err(CustomError::Sqlite(SqliteError{ - code: ffi::SQLITE_MISUSE, - message: "Invalid column index".to_owned(), - }))); - - let non_sqlite_err: CustomResult> = query - .query_and_then(&[], |_| Err(CustomError::SomeError)) - .unwrap() - .collect(); - - assert_eq!(non_sqlite_err, Err(CustomError::SomeError)); - } - #[test] fn test_query_row() { let db = checked_memory_handle(); @@ -1431,4 +1253,160 @@ mod test { assert!(format!("{:?}", stmt).contains(query)); } + + mod query_and_then_tests { + extern crate libsqlite3_sys as ffi; + use super::*; + + #[derive(Debug, PartialEq)] + enum CustomError { + SomeError, + Sqlite(SqliteError), + } + + impl fmt::Display for CustomError { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + CustomError::SomeError => write!(f, "{}", self.description()), + CustomError::Sqlite(ref se) => write!(f, "{}: {}", self.description(), se), + } + } + } + + impl StdError for CustomError { + fn description(&self) -> &str { "my custom error" } + fn cause(&self) -> Option<&StdError> { + match *self { + CustomError::SomeError => None, + CustomError::Sqlite(ref se) => Some(se), + } + } + } + + impl From for CustomError { + fn from(se: SqliteError) -> CustomError { + CustomError::Sqlite(se) + } + } + + type CustomResult = Result; + + #[test] + fn test_query_and_then() { + let db = checked_memory_handle(); + let sql = "BEGIN; + CREATE TABLE foo(x INTEGER, y TEXT); + INSERT INTO foo VALUES(4, \"hello\"); + INSERT INTO foo VALUES(3, \", \"); + INSERT INTO foo VALUES(2, \"world\"); + INSERT INTO foo VALUES(1, \"!\"); + END;"; + db.execute_batch(sql).unwrap(); + + let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap(); + let results: SqliteResult> = query + .query_and_then(&[], |row| row.get_checked(1)) + .unwrap() + .collect(); + + assert_eq!(results.unwrap().concat(), "hello, world!"); + } + + #[test] + fn test_query_and_then_fails() { + let db = checked_memory_handle(); + let sql = "BEGIN; + CREATE TABLE foo(x INTEGER, y TEXT); + INSERT INTO foo VALUES(4, \"hello\"); + INSERT INTO foo VALUES(3, \", \"); + INSERT INTO foo VALUES(2, \"world\"); + INSERT INTO foo VALUES(1, \"!\"); + END;"; + db.execute_batch(sql).unwrap(); + + let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap(); + let bad_type: SqliteResult> = query + .query_and_then(&[], |row| row.get_checked(1)) + .unwrap() + .collect(); + + assert_eq!(bad_type, Err(SqliteError{ + code: ffi::SQLITE_MISMATCH, + message: "Invalid column type".to_owned(), + })); + + let bad_idx: SqliteResult> = query + .query_and_then(&[], |row| row.get_checked(3)) + .unwrap() + .collect(); + + assert_eq!(bad_idx, Err(SqliteError{ + code: ffi::SQLITE_MISUSE, + message: "Invalid column index".to_owned(), + })); + } + + #[test] + fn test_query_and_then_custom_error() { + let db = checked_memory_handle(); + let sql = "BEGIN; + CREATE TABLE foo(x INTEGER, y TEXT); + INSERT INTO foo VALUES(4, \"hello\"); + INSERT INTO foo VALUES(3, \", \"); + INSERT INTO foo VALUES(2, \"world\"); + INSERT INTO foo VALUES(1, \"!\"); + END;"; + db.execute_batch(sql).unwrap(); + + let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap(); + let results: CustomResult> = query + .query_and_then(&[], |row| row.get_checked(1).map_err(CustomError::Sqlite)) + .unwrap() + .collect(); + + assert_eq!(results.unwrap().concat(), "hello, world!"); + } + + #[test] + fn test_query_and_then_custom_error_fails() { + let db = checked_memory_handle(); + let sql = "BEGIN; + CREATE TABLE foo(x INTEGER, y TEXT); + INSERT INTO foo VALUES(4, \"hello\"); + INSERT INTO foo VALUES(3, \", \"); + INSERT INTO foo VALUES(2, \"world\"); + INSERT INTO foo VALUES(1, \"!\"); + END;"; + db.execute_batch(sql).unwrap(); + + let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap(); + let bad_type: CustomResult> = query + .query_and_then(&[], |row| row.get_checked(1).map_err(CustomError::Sqlite)) + .unwrap() + .collect(); + + assert_eq!(bad_type, Err(CustomError::Sqlite(SqliteError{ + code: ffi::SQLITE_MISMATCH, + message: "Invalid column type".to_owned(), + }))); + + let bad_idx: CustomResult> = query + .query_and_then(&[], |row| row.get_checked(3).map_err(CustomError::Sqlite)) + .unwrap() + .collect(); + + assert_eq!(bad_idx, Err(CustomError::Sqlite(SqliteError{ + code: ffi::SQLITE_MISUSE, + message: "Invalid column index".to_owned(), + }))); + + let non_sqlite_err: CustomResult> = query + .query_and_then(&[], |_| Err(CustomError::SomeError)) + .unwrap() + .collect(); + + assert_eq!(non_sqlite_err, Err(CustomError::SomeError)); + } + + } } From 1918dc14d0419b42bb4765d30a989b4af121f757 Mon Sep 17 00:00:00 2001 From: John Gallagher Date: Sun, 20 Sep 2015 21:30:40 -0400 Subject: [PATCH 19/39] Add tests for query_row_and_then(). --- src/lib.rs | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index c142a1c..83d364d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1408,5 +1408,53 @@ mod test { assert_eq!(non_sqlite_err, Err(CustomError::SomeError)); } + #[test] + fn test_query_row_and_then_custom_error() { + let db = checked_memory_handle(); + let sql = "BEGIN; + CREATE TABLE foo(x INTEGER, y TEXT); + INSERT INTO foo VALUES(4, \"hello\"); + END;"; + db.execute_batch(sql).unwrap(); + + let query = "SELECT x, y FROM foo ORDER BY x DESC"; + let results: CustomResult = db + .query_row_and_then(query, &[], |row| row.get_checked(1).map_err(CustomError::Sqlite)); + + assert_eq!(results.unwrap(), "hello"); + } + + #[test] + fn test_query_row_and_then_custom_error_fails() { + let db = checked_memory_handle(); + let sql = "BEGIN; + CREATE TABLE foo(x INTEGER, y TEXT); + INSERT INTO foo VALUES(4, \"hello\"); + END;"; + db.execute_batch(sql).unwrap(); + + let query = "SELECT x, y FROM foo ORDER BY x DESC"; + let bad_type: CustomResult = db + .query_row_and_then(query, &[], |row| row.get_checked(1).map_err(CustomError::Sqlite)); + + assert_eq!(bad_type, Err(CustomError::Sqlite(SqliteError{ + code: ffi::SQLITE_MISMATCH, + message: "Invalid column type".to_owned(), + }))); + + let bad_idx: CustomResult = db + .query_row_and_then(query, &[], |row| row.get_checked(3).map_err(CustomError::Sqlite)); + + assert_eq!(bad_idx, Err(CustomError::Sqlite(SqliteError{ + code: ffi::SQLITE_MISUSE, + message: "Invalid column index".to_owned(), + }))); + + let non_sqlite_err: CustomResult = db + .query_row_and_then(query, &[], |_| Err(CustomError::SomeError)); + + assert_eq!(non_sqlite_err, Err(CustomError::SomeError)); + } + } } From 7ee69fe103f4a55f8f832fb47157e9992e692c9c Mon Sep 17 00:00:00 2001 From: John Gallagher Date: Mon, 21 Sep 2015 10:31:11 -0400 Subject: [PATCH 20/39] Remove get_opt (superceded by get_checked). --- src/lib.rs | 45 +++++++++++---------------------------------- 1 file changed, 11 insertions(+), 34 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 83d364d..fb3a50c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -941,7 +941,7 @@ impl<'stmt> SqliteRow<'stmt> { /// Panics if `idx` is outside the range of columns in the returned query or if this row /// is stale. pub fn get(&self, idx: c_int) -> T { - self.get_opt(idx).unwrap() + self.get_checked(idx).unwrap() } /// Get the value of a particular column of the result row. @@ -954,37 +954,6 @@ impl<'stmt> SqliteRow<'stmt> { /// Returns a `SQLITE_MISUSE`-coded `SqliteError` if `idx` is outside the valid column range /// for this row or if this row is stale. pub fn get_checked(&self, idx: c_int) -> SqliteResult { - if self.row_idx != self.current_row.get() { - return Err(SqliteError{ code: ffi::SQLITE_MISUSE, - message: "Cannot get values from a row after advancing to next row".to_string() }); - } - unsafe { - if idx < 0 || idx >= ffi::sqlite3_column_count(self.stmt.stmt) { - return Err(SqliteError{ code: ffi::SQLITE_MISUSE, - message: "Invalid column index".to_string() }); - } - } - let valid_column_type = unsafe { - T::column_has_valid_sqlite_type(self.stmt.stmt, idx) - }; - - if valid_column_type { - Ok(self.get(idx)) - } else { - Err(SqliteError{ - code: ffi::SQLITE_MISMATCH, - message: "Invalid column type".to_string(), - }) - } - } - - /// Attempt to get the value of a particular column of the result row. - /// - /// ## Failure - /// - /// Returns a `SQLITE_MISUSE`-coded `SqliteError` if `idx` is outside the valid column range - /// for this row or if this row is stale. - pub fn get_opt(&self, idx: c_int) -> SqliteResult { if self.row_idx != self.current_row.get() { return Err(SqliteError{ code: ffi::SQLITE_MISUSE, message: "Cannot get values from a row after advancing to next row".to_string() }); @@ -994,7 +963,15 @@ impl<'stmt> SqliteRow<'stmt> { return Err(SqliteError{ code: ffi::SQLITE_MISUSE, message: "Invalid column index".to_string() }); } - FromSql::column_result(self.stmt.stmt, idx) + + if T::column_has_valid_sqlite_type(self.stmt.stmt, idx) { + FromSql::column_result(self.stmt.stmt, idx) + } else { + Err(SqliteError{ + code: ffi::SQLITE_MISMATCH, + message: "Invalid column type".to_string(), + }) + } } } } @@ -1226,7 +1203,7 @@ mod test { assert_eq!(2i32, second.get(0)); - let result = first.get_opt::(0); + let result = first.get_checked::(0); assert!(result.unwrap_err().message.contains("advancing to next row")); } From c3bc8b594a40f12eecde0b05e262f2c03380f28d Mon Sep 17 00:00:00 2001 From: John Gallagher Date: Mon, 21 Sep 2015 10:39:13 -0400 Subject: [PATCH 21/39] Bump version to 0.3.0. Updates Changelog and CONTRIBUTORS for changes in this version. --- CONTRIBUTORS.md | 2 ++ Cargo.toml | 2 +- Changelog.md | 11 +++++++++++ 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 09b1187..e151714 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -5,3 +5,5 @@ rusqlite contributors (sorted alphabetically) * [Marcus Klaas de Vries](https://github.com/marcusklaas) * [gwenn](https://github.com/gwenn) * [Jimmy Lu](https://github.com/Yuhta) +* [Huon Wilson](https://github.com/huonw) +* [Patrick Fernie](https://github.com/pfernie) diff --git a/Cargo.toml b/Cargo.toml index 5d05ed5..0fbf0ee 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rusqlite" -version = "0.2.0" +version = "0.3.0" authors = ["John Gallagher "] description = "Ergonomic wrapper for SQLite" repository = "https://github.com/jgallagher/rusqlite" diff --git a/Changelog.md b/Changelog.md index 4fc6eff..6ce64d3 100644 --- a/Changelog.md +++ b/Changelog.md @@ -1,3 +1,14 @@ +# Version 0.3.0 (2015-09-21) + +* Removes `get_opt`. Use `get_checked` instead. +* Add `query_row_and_then` and `query_and_then` convenience functions. These are analogous to + `query_row` and `query_map` but allow functions that can fail by returning `Result`s. +* Relax uses of `P: AsRef<...>` from `&P` to `P`. +* Add additional error check for calling `execute` when `query` was intended. +* Improve debug formatting of `SqliteStatement` and `SqliteConnection`. +* Changes documentation of `get_checked` to correctly indicate that it returns errors (not panics) + when given invalid types or column indices. + # Version 0.2.0 (2015-07-26) * Add `column_names()` to `SqliteStatement`. From b41275cbc84bc19c9453cf723e05e3e18a70f144 Mon Sep 17 00:00:00 2001 From: John Gallagher Date: Tue, 22 Sep 2015 10:18:26 -0700 Subject: [PATCH 22/39] Update Changelog and Cargo.toml to 0.3.1 --- Cargo.toml | 2 +- Changelog.md | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 0fbf0ee..cd70b17 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rusqlite" -version = "0.3.0" +version = "0.3.1" authors = ["John Gallagher "] description = "Ergonomic wrapper for SQLite" repository = "https://github.com/jgallagher/rusqlite" diff --git a/Changelog.md b/Changelog.md index 6ce64d3..624b076 100644 --- a/Changelog.md +++ b/Changelog.md @@ -1,3 +1,8 @@ +# Version 0.3.1 (2015-09-22) + +* Reset underlying SQLite statements as soon as possible after executing, as recommended by + http://www.sqlite.org/cvstrac/wiki?p=ScrollingCursor. + # Version 0.3.0 (2015-09-21) * Removes `get_opt`. Use `get_checked` instead. From 420c4d4d9f05d0bb03fe2745f01933b8e59d5e6c Mon Sep 17 00:00:00 2001 From: John Gallagher Date: Tue, 3 Nov 2015 11:27:52 -0500 Subject: [PATCH 23/39] Address RFC 1214 warning --- src/types.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/types.rs b/src/types.rs index 5ad4ed7..a1d041f 100644 --- a/src/types.rs +++ b/src/types.rs @@ -74,7 +74,7 @@ pub trait ToSql { } /// A trait for types that can be created from a SQLite value. -pub trait FromSql { +pub trait FromSql: Sized { unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> SqliteResult; /// FromSql types can implement this method and use sqlite3_column_type to check that From 78979c44ee5f3ce804a63750346771393e645621 Mon Sep 17 00:00:00 2001 From: John Gallagher Date: Tue, 3 Nov 2015 11:29:02 -0500 Subject: [PATCH 24/39] Bump version to 0.4.0 --- Cargo.toml | 2 +- Changelog.md | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index cd70b17..68e7347 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rusqlite" -version = "0.3.1" +version = "0.4.0" authors = ["John Gallagher "] description = "Ergonomic wrapper for SQLite" repository = "https://github.com/jgallagher/rusqlite" diff --git a/Changelog.md b/Changelog.md index 624b076..2987801 100644 --- a/Changelog.md +++ b/Changelog.md @@ -1,3 +1,7 @@ +# Version 0.4.0 (2015-11-03) + +* Adds `Sized` bound to `FromSql` trait as required by RFC 1214. + # Version 0.3.1 (2015-09-22) * Reset underlying SQLite statements as soon as possible after executing, as recommended by From 270abfc44f5a153f6eec4f1728e60b901c8fd7eb Mon Sep 17 00:00:00 2001 From: John Gallagher Date: Tue, 3 Nov 2015 11:33:03 -0500 Subject: [PATCH 25/39] Update to travis CI's container-based infrastructure --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index e7cc210..837d9f4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,4 +1,5 @@ language: rust +sudo: false env: global: From 7586556db5b4ad4db94e5e6ab5232f8868b8f5c9 Mon Sep 17 00:00:00 2001 From: John Gallagher Date: Tue, 3 Nov 2015 11:37:23 -0500 Subject: [PATCH 26/39] Add to CONTRIBUTORS --- CONTRIBUTORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index e151714..24b0e7e 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -7,3 +7,4 @@ rusqlite contributors (sorted alphabetically) * [Jimmy Lu](https://github.com/Yuhta) * [Huon Wilson](https://github.com/huonw) * [Patrick Fernie](https://github.com/pfernie) +* [Steve Klabnik](https://github.com/steveklabnik) From 50bfba1e1d5192aa78069bf88fdc57236f2afb38 Mon Sep 17 00:00:00 2001 From: Gwenael Treguier Date: Wed, 11 Nov 2015 14:29:40 +0100 Subject: [PATCH 27/39] Ignore test_log. --- src/trace.rs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/trace.rs b/src/trace.rs index b3c9939..29473a2 100644 --- a/src/trace.rs +++ b/src/trace.rs @@ -75,11 +75,8 @@ mod test { } } - #[test] + #[test] #[ignore] // To avoid freezing tests fn test_log() { - if true { // To avoid freezing tests - return - } unsafe { ffi::sqlite3_shutdown() }; super::config_log(Some(log_callback)).unwrap(); //super::log(ffi::SQLITE_NOTICE, "message from rusqlite"); @@ -99,4 +96,4 @@ mod test { db.trace(Some(trace_callback)); db.execute_batch("PRAGMA application_id = 1").unwrap(); } -} \ No newline at end of file +} From a2327fb048c96297ecad41243b4b4d04dfb7367b Mon Sep 17 00:00:00 2001 From: Gwenael Treguier Date: Wed, 11 Nov 2015 15:00:39 +0100 Subject: [PATCH 28/39] Revert "Remove usage of unstable library feature 'duration'" This reverts commit 9c415f9c9e433101564767603e0be7aa341c7343. --- src/lib.rs | 1 + src/trace.rs | 10 ++++++---- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index c639831..c6f82ce 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -50,6 +50,7 @@ //! } //! } //! ``` +#![cfg_attr(test, feature(duration))] extern crate libc; extern crate libsqlite3_sys as ffi; #[macro_use] extern crate bitflags; diff --git a/src/trace.rs b/src/trace.rs index 29473a2..b024f13 100644 --- a/src/trace.rs +++ b/src/trace.rs @@ -83,17 +83,19 @@ mod test { super::config_log(None).unwrap(); } - extern "C" fn trace_callback(_: *mut ::libc::c_void, sql: *const ::libc::c_char) { + extern "C" fn profile_callback(_: *mut ::libc::c_void, sql: *const ::libc::c_char, nanoseconds: u64) { + use std::time::Duration; unsafe { let c_slice = ::std::ffi::CStr::from_ptr(sql).to_bytes(); - let _ = writeln!(::std::io::stderr(), "TRACE: {:?}", ::std::str::from_utf8(c_slice)); + let d = Duration::from_millis(nanoseconds / 1_000_000); + let _ = writeln!(::std::io::stderr(), "PROFILE: {:?} ({})", ::std::str::from_utf8(c_slice), d); } } #[test] - fn test_trace() { + fn test_profile() { let mut db = SqliteConnection::open_in_memory().unwrap(); - db.trace(Some(trace_callback)); + db.profile(Some(profile_callback)); db.execute_batch("PRAGMA application_id = 1").unwrap(); } } From 20c1213482ddd1bf5c19ebc4994b103f76d991f9 Mon Sep 17 00:00:00 2001 From: Gwenael Treguier Date: Wed, 11 Nov 2015 15:03:07 +0100 Subject: [PATCH 29/39] Remove feature duration. --- src/lib.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index c6f82ce..c639831 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -50,7 +50,6 @@ //! } //! } //! ``` -#![cfg_attr(test, feature(duration))] extern crate libc; extern crate libsqlite3_sys as ffi; #[macro_use] extern crate bitflags; From 0729e195c371fbab0898fdab6327682df9198169 Mon Sep 17 00:00:00 2001 From: Gwenael Treguier Date: Wed, 11 Nov 2015 15:14:31 +0100 Subject: [PATCH 30/39] Use debug_struct for formatting. --- src/lib.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 3b1c49e..b46232f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -444,7 +444,9 @@ impl SqliteConnection { impl fmt::Debug for SqliteConnection { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "SqliteConnection( path: {:?} )", &self.path) + f.debug_struct("SqliteConnection") + .field("path", &self.path) + .finish() } } @@ -780,7 +782,11 @@ impl<'conn> fmt::Debug for SqliteStatement<'conn> { let c_slice = CStr::from_ptr(ffi::sqlite3_sql(self.stmt)).to_bytes(); str::from_utf8(c_slice) }; - write!(f, "SqliteStatement( conn: {:?}, stmt: {:?}, sql: {:?} )", self.conn, self.stmt, sql) + f.debug_struct("SqliteStatement") + .field("conn", self.conn) + .field("stmt", &self.stmt) + .field("sql", &sql) + .finish() } } From dbfa6ca31f0c839dcc3afd33861d909265fd6f59 Mon Sep 17 00:00:00 2001 From: John Gallagher Date: Mon, 30 Nov 2015 15:29:50 -0500 Subject: [PATCH 31/39] Change config_log to take a Rust fn instead of an extern "C" fn. Moves the unit test for config_log out of #[ignore] and into its own test file since it affects the entire process. --- Cargo.toml | 5 ++++ src/trace.rs | 65 ++++++++++++++++++++++++--------------------- tests/config_log.rs | 36 +++++++++++++++++++++++++ 3 files changed, 76 insertions(+), 30 deletions(-) create mode 100644 tests/config_log.rs diff --git a/Cargo.toml b/Cargo.toml index 673044c..0078216 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,7 +23,12 @@ libc = "~0.1" [dev-dependencies] tempdir = "~0.3.4" +lazy_static = "~0.1" [dependencies.libsqlite3-sys] path = "libsqlite3-sys" version = "0.2.0" + +[[test]] +name = "config_log" +harness = false diff --git a/src/trace.rs b/src/trace.rs index b024f13..33b5997 100644 --- a/src/trace.rs +++ b/src/trace.rs @@ -1,31 +1,55 @@ //! Tracing and profiling functions. Error and warning log. + use libc::{c_char, c_int, c_void}; -use std::ffi::CString; +use std::ffi::{CStr, CString}; use std::ptr; +use std::str; use super::ffi; use {SqliteError, SqliteResult, SqliteConnection}; -pub type LogCallback = - Option; - -/// Set up the error logging callback +/// Set up the process-wide SQLite error logging callback. +/// This function is marked unsafe for two reasons: +/// +/// * The function is not threadsafe. No other SQLite calls may be made while +/// `config_log` is running, and multiple threads may not call `config_log` +/// simultaneously. +/// * The provided `callback` itself function has two requirements: +/// * It must not invoke any SQLite calls. +/// * It must be threadsafe if SQLite is used in a multithreaded way. /// /// cf [The Error And Warning Log](http://sqlite.org/errlog.html). -pub fn config_log(cb: LogCallback) -> SqliteResult<()> { - let rc = unsafe { - let p_arg: *mut c_void = ptr::null_mut(); - ffi::sqlite3_config(ffi::SQLITE_CONFIG_LOG, cb, p_arg) +pub unsafe fn config_log(callback: Option) -> SqliteResult<()> { + extern "C" fn log_callback(p_arg: *mut c_void, err: c_int, msg: *const c_char) { + let c_slice = unsafe { CStr::from_ptr(msg).to_bytes() }; + let callback: fn(c_int, &str) = unsafe { mem::transmute(p_arg) }; + + if let Ok(s) = str::from_utf8(c_slice) { + callback(err, s); + } + } + + let rc = match callback { + Some(f) => { + let p_arg: *mut c_void = mem::transmute(f); + ffi::sqlite3_config(ffi::SQLITE_CONFIG_LOG, Some(log_callback), p_arg) + }, + None => { + let nullptr: *mut c_void = ptr::null_mut(); + ffi::sqlite3_config(ffi::SQLITE_CONFIG_LOG, nullptr, nullptr) + } }; + if rc != ffi::SQLITE_OK { return Err(SqliteError{ code: rc, message: "sqlite3_config(SQLITE_CONFIG_LOG, ...)".to_string() }); } + Ok(()) } /// Write a message into the error log established by `config_log`. pub fn log(err_code: c_int, msg: &str) { - let msg = CString::new(msg).unwrap(); + let msg = CString::new(msg).expect("SQLite log messages cannot contain embedded zeroes"); unsafe { ffi::sqlite3_log(err_code, msg.as_ptr()); } @@ -60,35 +84,16 @@ impl SqliteConnection { #[cfg(test)] mod test { - use libc::{c_char, c_int, c_void}; - use std::ffi::CStr; use std::io::Write; - use std::str; - use ffi; use SqliteConnection; - extern "C" fn log_callback(_: *mut c_void, err: c_int, msg: *const c_char) { - unsafe { - let c_slice = CStr::from_ptr(msg).to_bytes(); - let _ = writeln!(::std::io::stderr(), "{}: {:?}", err, str::from_utf8(c_slice)); - } - } - - #[test] #[ignore] // To avoid freezing tests - fn test_log() { - unsafe { ffi::sqlite3_shutdown() }; - super::config_log(Some(log_callback)).unwrap(); - //super::log(ffi::SQLITE_NOTICE, "message from rusqlite"); - super::config_log(None).unwrap(); - } - extern "C" fn profile_callback(_: *mut ::libc::c_void, sql: *const ::libc::c_char, nanoseconds: u64) { use std::time::Duration; unsafe { let c_slice = ::std::ffi::CStr::from_ptr(sql).to_bytes(); let d = Duration::from_millis(nanoseconds / 1_000_000); - let _ = writeln!(::std::io::stderr(), "PROFILE: {:?} ({})", ::std::str::from_utf8(c_slice), d); + let _ = writeln!(::std::io::stderr(), "PROFILE: {:?} ({:?})", ::std::str::from_utf8(c_slice), d); } } diff --git a/tests/config_log.rs b/tests/config_log.rs new file mode 100644 index 0000000..e0167bd --- /dev/null +++ b/tests/config_log.rs @@ -0,0 +1,36 @@ +//! This file contains unit tests for rusqlite::trace::config_log. This function affects +//! SQLite process-wide and so is not safe to run as a normal #[test] in the library. + +#[macro_use] extern crate lazy_static; +extern crate libc; +extern crate rusqlite; + +#[cfg(feature = "trace")] +fn main() { + use libc::c_int; + use std::sync::Mutex; + + lazy_static! { + static ref LOGS_RECEIVED: Mutex> = Mutex::new(Vec::new()); + } + + fn log_handler(err: c_int, message: &str) { + let mut logs_received = LOGS_RECEIVED.lock().unwrap(); + logs_received.push((err, message.to_owned())); + } + + use rusqlite::trace; + + unsafe { trace::config_log(Some(log_handler)) }.unwrap(); + trace::log(10, "First message from rusqlite"); + unsafe { trace::config_log(None) }.unwrap(); + trace::log(11, "Second message from rusqlite"); + + let logs_received = LOGS_RECEIVED.lock().unwrap(); + assert_eq!(logs_received.len(), 1); + assert_eq!(logs_received[0].0, 10); + assert_eq!(logs_received[0].1, "First message from rusqlite"); +} + +#[cfg(not(feature = "trace"))] +fn main() {} From ace5b1ebdc2e9d31cda1a7bbd928fc09b12f8722 Mon Sep 17 00:00:00 2001 From: John Gallagher Date: Mon, 30 Nov 2015 16:33:47 -0500 Subject: [PATCH 32/39] Change trace() to take a Rust fn instead of an extern "C" fn. --- src/lib.rs | 10 +--------- src/trace.rs | 49 ++++++++++++++++++++++++++++++++++++++++++++----- 2 files changed, 45 insertions(+), 14 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index d11b98a..cd24ad9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -53,6 +53,7 @@ extern crate libc; extern crate libsqlite3_sys as ffi; #[macro_use] extern crate bitflags; +#[cfg(test)] #[macro_use] extern crate lazy_static; use std::default::Default; use std::convert; @@ -142,15 +143,6 @@ fn path_to_cstring(p: &Path) -> SqliteResult { } /// A connection to a SQLite database. -/// -/// ## Warning -/// -/// Note that despite the fact that most `SqliteConnection` methods take an immutable reference to -/// `self`, `SqliteConnection` is NOT threadsafe, and using it from multiple threads may result in -/// runtime panics or data races. The SQLite connection handle has at least two pieces of internal -/// state (the last insertion ID and the last error message) that rusqlite uses, but wrapping these -/// APIs in a safe way from Rust would be too restrictive (for example, you would not be able to -/// prepare multiple statements at the same time). pub struct SqliteConnection { db: RefCell, path: Option, diff --git a/src/trace.rs b/src/trace.rs index 33b5997..1777057 100644 --- a/src/trace.rs +++ b/src/trace.rs @@ -2,6 +2,7 @@ use libc::{c_char, c_int, c_void}; use std::ffi::{CStr, CString}; +use std::mem; use std::ptr; use std::str; @@ -55,9 +56,6 @@ pub fn log(err_code: c_int, msg: &str) { } } -/// The trace callback function signature. -pub type TraceCallback = - Option; /// The profile callback function signature. pub type ProfileCallback = Option; @@ -68,10 +66,22 @@ impl SqliteConnection { /// Prepared statement placeholders are replaced/logged with their assigned values. /// There can only be a single tracer defined for each database connection. /// Setting a new tracer clears the old one. - pub fn trace(&mut self, x_trace: TraceCallback) { + pub fn trace(&mut self, trace_fn: Option) { + extern "C" fn trace_callback (p_arg: *mut c_void, z_sql: *const c_char) { + let trace_fn: fn(&str) = unsafe { mem::transmute(p_arg) }; + let c_slice = unsafe { CStr::from_ptr(z_sql).to_bytes() }; + if let Ok(s) = str::from_utf8(c_slice) { + trace_fn(s); + } + } + let c = self.db.borrow_mut(); - unsafe { ffi::sqlite3_trace(c.db(), x_trace, ptr::null_mut()); } + match trace_fn { + Some(f) => unsafe { ffi::sqlite3_trace(c.db(), Some(trace_callback), mem::transmute(f)); }, + None => unsafe { ffi::sqlite3_trace(c.db(), None, ptr::null_mut()); }, + } } + /// Register or clear a callback function that can be used for profiling the execution of SQL statements. /// /// There can only be a single profiler defined for each database connection. @@ -85,9 +95,38 @@ impl SqliteConnection { #[cfg(test)] mod test { use std::io::Write; + use std::sync::Mutex; use SqliteConnection; + #[test] + fn test_trace() { + lazy_static! { + static ref TRACED_STMTS: Mutex> = Mutex::new(Vec::new()); + } + fn tracer(s: &str) { + let mut traced_stmts = TRACED_STMTS.lock().unwrap(); + traced_stmts.push(s.to_owned()); + } + + let mut db = SqliteConnection::open_in_memory().unwrap(); + db.trace(Some(tracer)); + { + let _ = db.query_row("SELECT ?", &[&1i32], |_| {}); + let _ = db.query_row("SELECT ?", &[&"hello"], |_| {}); + } + db.trace(None); + { + let _ = db.query_row("SELECT ?", &[&2i32], |_| {}); + let _ = db.query_row("SELECT ?", &[&"goodbye"], |_| {}); + } + + let traced_stmts = TRACED_STMTS.lock().unwrap(); + assert_eq!(traced_stmts.len(), 2); + assert_eq!(traced_stmts[0], "SELECT 1"); + assert_eq!(traced_stmts[1], "SELECT 'hello'"); + } + extern "C" fn profile_callback(_: *mut ::libc::c_void, sql: *const ::libc::c_char, nanoseconds: u64) { use std::time::Duration; unsafe { From 8e31a64dde26a7c404ea75e4d8a603b32c37ce16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Krasnoborski?= Date: Tue, 1 Dec 2015 06:18:44 +0000 Subject: [PATCH 33/39] Update Cargo.tomls to libc ~0.2 --- Cargo.toml | 2 +- libsqlite3-sys/Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 68e7347..1efbe76 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,7 +18,7 @@ load_extension = ["libsqlite3-sys/load_extension"] [dependencies] time = "~0.1.0" bitflags = "~0.1" -libc = "~0.1" +libc = "~0.2" [dev-dependencies] tempdir = "~0.3.4" diff --git a/libsqlite3-sys/Cargo.toml b/libsqlite3-sys/Cargo.toml index ecb20b8..cafa632 100644 --- a/libsqlite3-sys/Cargo.toml +++ b/libsqlite3-sys/Cargo.toml @@ -15,4 +15,4 @@ load_extension = [] pkg-config = "~0.3" [dependencies] -libc = "~0.1" +libc = "~0.2" From e6fef5107dd599bb4dd8dcec12fbb1889bf3334f Mon Sep 17 00:00:00 2001 From: John Gallagher Date: Tue, 1 Dec 2015 10:34:18 -0500 Subject: [PATCH 34/39] Change profile() to take a Rust fn instead of an extern "C" fn. --- src/trace.rs | 51 ++++++++++++++++++++++++++++++++++----------------- 1 file changed, 34 insertions(+), 17 deletions(-) diff --git a/src/trace.rs b/src/trace.rs index 1777057..4296ddc 100644 --- a/src/trace.rs +++ b/src/trace.rs @@ -5,6 +5,7 @@ use std::ffi::{CStr, CString}; use std::mem; use std::ptr; use std::str; +use std::time::Duration; use super::ffi; use {SqliteError, SqliteResult, SqliteConnection}; @@ -56,10 +57,6 @@ pub fn log(err_code: c_int, msg: &str) { } } -/// The profile callback function signature. -pub type ProfileCallback = - Option; - impl SqliteConnection { /// Register or clear a callback function that can be used for tracing the execution of SQL statements. /// @@ -86,16 +83,31 @@ impl SqliteConnection { /// /// There can only be a single profiler defined for each database connection. /// Setting a new profiler clears the old one. - pub fn profile(&mut self, x_profile: ProfileCallback) { + pub fn profile(&mut self, profile_fn: Option) { + extern "C" fn profile_callback(p_arg: *mut c_void, z_sql: *const c_char, nanoseconds: u64) { + let profile_fn: fn(&str, Duration) = unsafe { mem::transmute(p_arg) }; + let c_slice = unsafe { CStr::from_ptr(z_sql).to_bytes() }; + if let Ok(s) = str::from_utf8(c_slice) { + const NANOS_PER_SEC: u64 = 1_000_000_000; + + let duration = Duration::new(nanoseconds / NANOS_PER_SEC, + (nanoseconds % NANOS_PER_SEC) as u32); + profile_fn(s, duration); + } + } + let c = self.db.borrow_mut(); - unsafe { ffi::sqlite3_profile(c.db(), x_profile, ptr::null_mut()); } + match profile_fn { + Some(f) => unsafe { ffi::sqlite3_profile(c.db(), Some(profile_callback), mem::transmute(f)) }, + None => unsafe { ffi::sqlite3_profile(c.db(), None, ptr::null_mut()) }, + }; } } #[cfg(test)] mod test { - use std::io::Write; use std::sync::Mutex; + use std::time::Duration; use SqliteConnection; @@ -127,19 +139,24 @@ mod test { assert_eq!(traced_stmts[1], "SELECT 'hello'"); } - extern "C" fn profile_callback(_: *mut ::libc::c_void, sql: *const ::libc::c_char, nanoseconds: u64) { - use std::time::Duration; - unsafe { - let c_slice = ::std::ffi::CStr::from_ptr(sql).to_bytes(); - let d = Duration::from_millis(nanoseconds / 1_000_000); - let _ = writeln!(::std::io::stderr(), "PROFILE: {:?} ({:?})", ::std::str::from_utf8(c_slice), d); - } - } - #[test] fn test_profile() { + lazy_static! { + static ref PROFILED: Mutex> = Mutex::new(Vec::new()); + } + fn profiler(s: &str, d: Duration) { + let mut profiled = PROFILED.lock().unwrap(); + profiled.push((s.to_owned(), d)); + } + let mut db = SqliteConnection::open_in_memory().unwrap(); - db.profile(Some(profile_callback)); + db.profile(Some(profiler)); db.execute_batch("PRAGMA application_id = 1").unwrap(); + db.profile(None); + db.execute_batch("PRAGMA application_id = 2").unwrap(); + + let profiled = PROFILED.lock().unwrap(); + assert_eq!(profiled.len(), 1); + assert_eq!(profiled[0].0, "PRAGMA application_id = 1"); } } From cba64a7deee3a372612410b3634dc9e822b91e85 Mon Sep 17 00:00:00 2001 From: John Gallagher Date: Tue, 1 Dec 2015 10:37:01 -0500 Subject: [PATCH 35/39] Add trace feature to Changelog --- Changelog.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Changelog.md b/Changelog.md index 2987801..5a1eaec 100644 --- a/Changelog.md +++ b/Changelog.md @@ -1,3 +1,7 @@ +# Version UPCOMING (TBD) + +* Adds `trace` feature that allows the use of SQLite's logging, tracing, and profiling hooks. + # Version 0.4.0 (2015-11-03) * Adds `Sized` bound to `FromSql` trait as required by RFC 1214. From 86165725de1b7a0b820f6d3a197f44aace22d561 Mon Sep 17 00:00:00 2001 From: John Gallagher Date: Tue, 1 Dec 2015 10:43:55 -0500 Subject: [PATCH 36/39] Add krdln to CONTRIBUTORS --- CONTRIBUTORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 24b0e7e..eca404b 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -8,3 +8,4 @@ rusqlite contributors (sorted alphabetically) * [Huon Wilson](https://github.com/huonw) * [Patrick Fernie](https://github.com/pfernie) * [Steve Klabnik](https://github.com/steveklabnik) +* [krdln](https://github.com/krdln) From 635616842cea1171dea7a0d4a92fa8d64dec50bd Mon Sep 17 00:00:00 2001 From: John Gallagher Date: Tue, 1 Dec 2015 10:55:01 -0500 Subject: [PATCH 37/39] Remove 'static requirement on output of closure given to query_map and query_and_then. The 'static bound was there to prevent callers from being able to save off the `SqliteRow` handles passed into the closure. This PR changes the closure to take `&SqliteRow`s instead, which provides the same feature without restricting the output of the closure. --- Changelog.md | 6 ++++++ README.md | 2 +- src/lib.rs | 20 ++++++++------------ 3 files changed, 15 insertions(+), 13 deletions(-) diff --git a/Changelog.md b/Changelog.md index 2987801..0af134a 100644 --- a/Changelog.md +++ b/Changelog.md @@ -1,3 +1,9 @@ +# Version UPCOMDING (TBD) + +* Slight change to the closure types passed to `query_map` and `query_and_then`: + * Remove the `'static` requirement on the closure's output type. + * Give the closure a `&SqliteRow` instead of a `SqliteRow`. + # Version 0.4.0 (2015-11-03) * Adds `Sized` bound to `FromSql` trait as required by RFC 1214. diff --git a/README.md b/README.md index 990af8d..1bc6742 100644 --- a/README.md +++ b/README.md @@ -91,7 +91,7 @@ There are other, less obvious things that may result in a panic as well, such as `collect()` on a `SqliteRows` and then trying to use the collected rows. Strongly consider using the method `query_map()` instead, if you can. -`query_map()` returns an iterator over rows-mapped-to-some-`'static`-type. This +`query_map()` returns an iterator over rows-mapped-to-some-type. This iterator does not have any of the above issues with panics due to attempting to access stale rows. diff --git a/src/lib.rs b/src/lib.rs index b46232f..cae3c59 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -712,8 +712,7 @@ impl<'conn> SqliteStatement<'conn> { /// for accessing stale rows. pub fn query_map<'a, T, F>(&'a mut self, params: &[&ToSql], f: F) -> SqliteResult> - where T: 'static, - F: FnMut(SqliteRow) -> T { + where F: FnMut(&SqliteRow) -> T { let row_iter = try!(self.query(params)); Ok(MappedRows{ @@ -730,9 +729,8 @@ impl<'conn> SqliteStatement<'conn> { /// for accessing stale rows. pub fn query_and_then<'a, T, E, F>(&'a mut self, params: &[&ToSql], f: F) -> SqliteResult> - where T: 'static, - E: convert::From, - F: FnMut(SqliteRow) -> Result { + where E: convert::From, + F: FnMut(&SqliteRow) -> Result { let row_iter = try!(self.query(params)); Ok(AndThenRows{ @@ -804,12 +802,11 @@ pub struct MappedRows<'stmt, F> { } impl<'stmt, T, F> Iterator for MappedRows<'stmt, F> - where T: 'static, - F: FnMut(SqliteRow) -> T { + where F: FnMut(&SqliteRow) -> T { type Item = SqliteResult; fn next(&mut self) -> Option> { - self.rows.next().map(|row_result| row_result.map(|row| (self.map)(row))) + self.rows.next().map(|row_result| row_result.map(|row| (self.map)(&row))) } } @@ -821,15 +818,14 @@ pub struct AndThenRows<'stmt, F> { } impl<'stmt, T, E, F> Iterator for AndThenRows<'stmt, F> - where T: 'static, - E: convert::From, - F: FnMut(SqliteRow) -> Result { + where E: convert::From, + F: FnMut(&SqliteRow) -> Result { type Item = Result; fn next(&mut self) -> Option { self.rows.next().map(|row_result| row_result .map_err(E::from) - .and_then(|row| (self.map)(row))) + .and_then(|row| (self.map)(&row))) } } From 1af3fcd0539a7699ae13d7707d62d6d2f5585491 Mon Sep 17 00:00:00 2001 From: John Gallagher Date: Tue, 1 Dec 2015 11:47:55 -0500 Subject: [PATCH 38/39] Fix error messages when failing to convert paths and strings to C-compatible versions --- src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index cae3c59..364d6d9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -128,14 +128,14 @@ impl SqliteError { fn str_to_cstring(s: &str) -> SqliteResult { CString::new(s).map_err(|_| SqliteError{ code: ffi::SQLITE_MISUSE, - message: "Could not convert path to C-combatible string".to_string() + message: format!("Could not convert string {} to C-combatible string", s), }) } fn path_to_cstring(p: &Path) -> SqliteResult { let s = try!(p.to_str().ok_or(SqliteError{ code: ffi::SQLITE_MISUSE, - message: "Could not convert path to UTF-8 string".to_string() + message: format!("Could not convert path {} to UTF-8 string", p.to_string_lossy()), })); str_to_cstring(s) } From 3d654aeed17c22c084764bef48a3d5ad7cd35730 Mon Sep 17 00:00:00 2001 From: John Gallagher Date: Tue, 1 Dec 2015 12:05:29 -0500 Subject: [PATCH 39/39] Add more documentation for failure modes of functions that return s --- CONTRIBUTORS.md | 1 + Changelog.md | 1 + src/lib.rs | 88 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 90 insertions(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index eca404b..61121a5 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -9,3 +9,4 @@ rusqlite contributors (sorted alphabetically) * [Patrick Fernie](https://github.com/pfernie) * [Steve Klabnik](https://github.com/steveklabnik) * [krdln](https://github.com/krdln) +* [Ben Striegel](https://github.com/bstrie) diff --git a/Changelog.md b/Changelog.md index 0af134a..f5e1775 100644 --- a/Changelog.md +++ b/Changelog.md @@ -3,6 +3,7 @@ * Slight change to the closure types passed to `query_map` and `query_and_then`: * Remove the `'static` requirement on the closure's output type. * Give the closure a `&SqliteRow` instead of a `SqliteRow`. +* Add more documentation for failure modes of functions that return `SqliteResult`s. # Version 0.4.0 (2015-11-03) diff --git a/src/lib.rs b/src/lib.rs index 364d6d9..1e77854 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -162,12 +162,21 @@ impl SqliteConnection { /// /// `SqliteConnection::open(path)` is equivalent to `SqliteConnection::open_with_flags(path, /// SQLITE_OPEN_READ_WRITE | SQLITE_OPEN_CREATE)`. + /// + /// # Failure + /// + /// Will return `Err` if `path` cannot be converted to a C-compatible string or if the + /// underlying SQLite open call fails. pub fn open>(path: P) -> SqliteResult { let flags = Default::default(); SqliteConnection::open_with_flags(path, flags) } /// Open a new connection to an in-memory SQLite database. + /// + /// # Failure + /// + /// Will return `Err` if the underlying SQLite open call fails. pub fn open_in_memory() -> SqliteResult { let flags = Default::default(); SqliteConnection::open_in_memory_with_flags(flags) @@ -177,6 +186,11 @@ impl SqliteConnection { /// /// Database Connection](http://www.sqlite.org/c3ref/open.html) for a description of valid /// flag combinations. + /// + /// # Failure + /// + /// Will return `Err` if `path` cannot be converted to a C-compatible string or if the + /// underlying SQLite open call fails. pub fn open_with_flags>(path: P, flags: SqliteOpenFlags) -> SqliteResult { let c_path = try!(path_to_cstring(path.as_ref())); @@ -189,6 +203,10 @@ impl SqliteConnection { /// /// Database Connection](http://www.sqlite.org/c3ref/open.html) for a description of valid /// flag combinations. + /// + /// # Failure + /// + /// Will return `Err` if the underlying SQLite open call fails. pub fn open_in_memory_with_flags(flags: SqliteOpenFlags) -> SqliteResult { let c_memory = try!(str_to_cstring(":memory:")); InnerSqliteConnection::open_with_flags(&c_memory, flags).map(|db| { @@ -216,6 +234,10 @@ impl SqliteConnection { /// tx.commit() /// } /// ``` + /// + /// # Failure + /// + /// Will return `Err` if the underlying SQLite call fails. pub fn transaction<'a>(&'a self) -> SqliteResult> { SqliteTransaction::new(self, SqliteTransactionDeferred) } @@ -223,6 +245,10 @@ impl SqliteConnection { /// Begin a new transaction with a specified behavior. /// /// See `transaction`. + /// + /// # Failure + /// + /// Will return `Err` if the underlying SQLite call fails. pub fn transaction_with_behavior<'a>(&'a self, behavior: SqliteTransactionBehavior) -> SqliteResult> { SqliteTransaction::new(self, behavior) @@ -243,6 +269,11 @@ impl SqliteConnection { /// COMMIT;") /// } /// ``` + /// + /// # Failure + /// + /// Will return `Err` if `sql` cannot be converted to a C-compatible string or if the + /// underlying SQLite call fails. pub fn execute_batch(&self, sql: &str) -> SqliteResult<()> { self.db.borrow_mut().execute_batch(sql) } @@ -263,6 +294,11 @@ impl SqliteConnection { /// } /// } /// ``` + /// + /// # Failure + /// + /// Will return `Err` if `sql` cannot be converted to a C-compatible string or if the + /// underlying SQLite call fails. pub fn execute(&self, sql: &str, params: &[&ToSql]) -> SqliteResult { self.prepare(sql).and_then(|mut stmt| stmt.execute(params)) } @@ -289,6 +325,11 @@ impl SqliteConnection { /// ``` /// /// If the query returns more than one row, all rows except the first are ignored. + /// + /// # Failure + /// + /// Will return `Err` if `sql` cannot be converted to a C-compatible string or if the + /// underlying SQLite call fails. pub fn query_row(&self, sql: &str, params: &[&ToSql], f: F) -> SqliteResult where F: FnOnce(SqliteRow) -> T { let mut stmt = try!(self.prepare(sql)); @@ -319,6 +360,11 @@ impl SqliteConnection { /// ``` /// /// If the query returns more than one row, all rows except the first are ignored. + /// + /// # Failure + /// + /// Will return `Err` if `sql` cannot be converted to a C-compatible string or if the + /// underlying SQLite call fails. pub fn query_row_and_then(&self, sql: &str, params: &[&ToSql], f: F) -> Result where F: FnOnce(SqliteRow) -> Result, E: convert::From { @@ -371,6 +417,11 @@ impl SqliteConnection { /// Ok(()) /// } /// ``` + /// + /// # Failure + /// + /// Will return `Err` if `sql` cannot be converted to a C-compatible string or if the + /// underlying SQLite call fails. pub fn prepare<'a>(&'a self, sql: &str) -> SqliteResult> { self.db.borrow_mut().prepare(self, sql) } @@ -379,6 +430,10 @@ impl SqliteConnection { /// /// This is functionally equivalent to the `Drop` implementation for `SqliteConnection` except /// that it returns any error encountered to the caller. + /// + /// # Failure + /// + /// Will return `Err` if the underlying SQLite call fails. pub fn close(self) -> SqliteResult<()> { let mut db = self.db.borrow_mut(); db.close() @@ -398,6 +453,10 @@ impl SqliteConnection { /// conn.load_extension_disable() /// } /// ``` + /// + /// # Failure + /// + /// Will return `Err` if the underlying SQLite call fails. #[cfg(feature = "load_extension")] pub fn load_extension_enable(&self) -> SqliteResult<()> { self.db.borrow_mut().enable_load_extension(1) @@ -406,6 +465,10 @@ impl SqliteConnection { /// Disable loading of SQLite extensions. /// /// See `load_extension_enable` for an example. + /// + /// # Failure + /// + /// Will return `Err` if the underlying SQLite call fails. #[cfg(feature = "load_extension")] pub fn load_extension_disable(&self) -> SqliteResult<()> { self.db.borrow_mut().enable_load_extension(0) @@ -428,6 +491,10 @@ impl SqliteConnection { /// /// conn.load_extension("my_sqlite_extension", None) /// } + /// + /// # Failure + /// + /// Will return `Err` if the underlying SQLite call fails. #[cfg(feature = "load_extension")] pub fn load_extension>(&self, dylib_path: P, entry_point: Option<&str>) -> SqliteResult<()> { self.db.borrow_mut().load_extension(dylib_path, entry_point) @@ -653,6 +720,11 @@ impl<'conn> SqliteStatement<'conn> { /// Ok(()) /// } /// ``` + /// + /// # Failure + /// + /// Will return `Err` if binding parameters fails, the executed statement returns rows (in + /// which case `query` should be used instead), or the underling SQLite call fails. pub fn execute(&mut self, params: &[&ToSql]) -> SqliteResult { unsafe { try!(self.bind_parameters(params)); @@ -694,6 +766,10 @@ impl<'conn> SqliteStatement<'conn> { /// Ok(names) /// } /// ``` + /// + /// # Failure + /// + /// Will return `Err` if binding parameters fails. pub fn query<'a>(&'a mut self, params: &[&ToSql]) -> SqliteResult> { self.reset_if_needed(); @@ -710,6 +786,10 @@ impl<'conn> SqliteStatement<'conn> { /// /// Unlike the iterator produced by `query`, the returned iterator does not expose the possibility /// for accessing stale rows. + /// + /// # Failure + /// + /// Will return `Err` if binding parameters fails. pub fn query_map<'a, T, F>(&'a mut self, params: &[&ToSql], f: F) -> SqliteResult> where F: FnMut(&SqliteRow) -> T { @@ -727,6 +807,10 @@ impl<'conn> SqliteStatement<'conn> { /// /// Unlike the iterator produced by `query`, the returned iterator does not expose the possibility /// for accessing stale rows. + /// + /// # Failure + /// + /// Will return `Err` if binding parameters fails. pub fn query_and_then<'a, T, E, F>(&'a mut self, params: &[&ToSql], f: F) -> SqliteResult> where E: convert::From, @@ -743,6 +827,10 @@ impl<'conn> SqliteStatement<'conn> { /// /// Functionally equivalent to the `Drop` implementation, but allows callers to see any errors /// that occur. + /// + /// # Failure + /// + /// Will return `Err` if the underlying SQLite call fails. pub fn finalize(mut self) -> SqliteResult<()> { self.finalize_() }