diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 39264b7..3fbb310 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -11,3 +11,4 @@ rusqlite contributors (sorted alphabetically) * [krdln](https://github.com/krdln) * [Ben Striegel](https://github.com/bstrie) * [Andrew Straw](https://github.com/astraw) +* [Ronald Kinard](https://github.com/Furyhunter) diff --git a/Changelog.md b/Changelog.md index d3c78b4..00f2b20 100644 --- a/Changelog.md +++ b/Changelog.md @@ -1,5 +1,21 @@ # Version UPCOMING (TBD) +* BREAKING CHANGE: `SqliteTransactionDeferred`, `SqliteTransactionImmediate`, and + `SqliteTransactionExclusive` are no longer exported. Instead, use + `TransactionBehavior::Deferred`, `TransactionBehavior::Immediate`, and + `TransactionBehavior::Exclusive`. +* Removed `Sqlite` prefix on many types: + * `SqliteConnection` is now `Connection` + * `SqliteError` is now `Error` + * `SqliteResult` is now `Result` + * `SqliteStatement` is now `Statement` + * `SqliteRows` is now `Rows` + * `SqliteRow` is now `Row` + * `SqliteOpenFlags` is now `OpenFlags` + * `SqliteTransaction` is now `Transaction`. + * `SqliteTransactionBehavior` is now `TransactionBehavior`. + * `SqliteLoadExtensionGuard` is now `LoadExtensionGuard`. + The old, prefixed names are still exported but are deprecated. * Adds a variety of `..._named` methods for executing queries using named placeholder parameters. * Adds `backup` feature that exposes SQLite's online backup API. * Adds `functions` feature that allows user-defined scalar functions to be added to diff --git a/README.md b/README.md index 1bc6742..9d78640 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ extern crate rusqlite; extern crate time; use time::Timespec; -use rusqlite::SqliteConnection; +use rusqlite::Connection; #[derive(Debug)] struct Person { @@ -22,7 +22,7 @@ struct Person { } fn main() { - let conn = SqliteConnection::open_in_memory().unwrap(); + let conn = Connection::open_in_memory().unwrap(); conn.execute("CREATE TABLE person ( id INTEGER PRIMARY KEY, @@ -56,7 +56,7 @@ fn main() { } ``` -### Design of SqliteRows and SqliteRow +### Design of Rows and Row To retrieve the result rows from a query, SQLite requires you to call [sqlite3_step()](https://www.sqlite.org/c3ref/step.html) on a prepared statement. You can only @@ -67,12 +67,12 @@ satisfy the [Iterator](http://doc.rust-lang.org/std/iter/trait.Iterator.html) tr you cannot (as easily) loop over the rows, or use many of the helpful Iterator methods like `map` and `filter`. -Instead, Rusqlite's `SqliteRows` handle does conform to `Iterator`. It ensures safety by +Instead, Rusqlite's `Rows` handle does conform to `Iterator`. It ensures safety by performing checks at runtime to ensure you do not try to retrieve the values of a "stale" row, and will panic if you do so. A specific example that will panic: ```rust -fn bad_function_will_panic(conn: &SqliteConnection) -> SqliteResult { +fn bad_function_will_panic(conn: &Connection) -> Result { let mut stmt = try!(conn.prepare("SELECT id FROM my_table")); let mut rows = try!(stmt.query(&[])); @@ -88,7 +88,7 @@ fn bad_function_will_panic(conn: &SqliteConnection) -> SqliteResult { ``` There are other, less obvious things that may result in a panic as well, such as calling -`collect()` on a `SqliteRows` and then trying to use the collected rows. +`collect()` on a `Rows` 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-type. This diff --git a/src/backup.rs b/src/backup.rs index e50ad20..8eb5625 100644 --- a/src/backup.rs +++ b/src/backup.rs @@ -1,6 +1,6 @@ //! Online SQLite backup API. //! -//! To create a `Backup`, you must have two distinct `SqliteConnection`s - one +//! To create a `Backup`, you must have two distinct `Connection`s - one //! for the source (which can be used while the backup is running) and one for //! the destination (which cannot). A `Backup` handle exposes three methods: //! `step` will attempt to back up a specified number of pages, `progress` gets @@ -14,13 +14,13 @@ //! documentation](https://www.sqlite.org/backup.html). //! //! ```rust,no_run -//! # use rusqlite::{backup, SqliteConnection, SqliteResult}; +//! # use rusqlite::{backup, Connection, Result}; //! # use std::path::Path; //! # use std::time; //! -//! fn backupDb>(src: &SqliteConnection, dst: P, progress: fn(backup::Progress)) -//! -> SqliteResult<()> { -//! let mut dst = try!(SqliteConnection::open(dst)); +//! fn backupDb>(src: &Connection, dst: P, progress: fn(backup::Progress)) +//! -> Result<()> { +//! let mut dst = try!(Connection::open(dst)); //! let backup = try!(backup::Backup::new(src, &mut dst)); //! backup.run_to_completion(5, time::Duration::from_millis(250), Some(progress)) //! } @@ -36,9 +36,9 @@ use std::time::Duration; use ffi; -use {DatabaseName, SqliteConnection, SqliteError, SqliteResult}; +use {DatabaseName, Connection, Error, Result}; -impl SqliteConnection { +impl Connection { /// Back up the `name` database to the given destination path. /// If `progress` is not `None`, it will be called periodically /// until the backup completes. @@ -55,9 +55,9 @@ impl SqliteConnection { name: DatabaseName, dst_path: P, progress: Option) - -> SqliteResult<()> { + -> Result<()> { use self::StepResult::{More, Done, Busy, Locked}; - let mut dst = try!(SqliteConnection::open(dst_path)); + let mut dst = try!(Connection::open(dst_path)); let backup = try!(Backup::new_with_names(self, name, &mut dst, DatabaseName::Main)); let mut r = More; @@ -70,8 +70,8 @@ impl SqliteConnection { match r { Done => Ok(()), - Busy => Err(SqliteError::from_handle(ptr::null_mut(), ffi::SQLITE_BUSY)), - Locked => Err(SqliteError::from_handle(ptr::null_mut(), ffi::SQLITE_LOCKED)), + Busy => Err(Error::from_handle(ptr::null_mut(), ffi::SQLITE_BUSY)), + Locked => Err(Error::from_handle(ptr::null_mut(), ffi::SQLITE_LOCKED)), More => unreachable!(), } } @@ -92,9 +92,9 @@ impl SqliteConnection { name: DatabaseName, src_path: P, progress: Option) - -> SqliteResult<()> { + -> Result<()> { use self::StepResult::{More, Done, Busy, Locked}; - let src = try!(SqliteConnection::open(src_path)); + let src = try!(Connection::open(src_path)); let restore = try!(Backup::new_with_names(&src, DatabaseName::Main, self, name)); let mut r = More; @@ -115,8 +115,8 @@ impl SqliteConnection { match r { Done => Ok(()), - Busy => Err(SqliteError::from_handle(ptr::null_mut(), ffi::SQLITE_BUSY)), - Locked => Err(SqliteError::from_handle(ptr::null_mut(), ffi::SQLITE_LOCKED)), + Busy => Err(Error::from_handle(ptr::null_mut(), ffi::SQLITE_BUSY)), + Locked => Err(Error::from_handle(ptr::null_mut(), ffi::SQLITE_LOCKED)), More => unreachable!(), } } @@ -170,9 +170,9 @@ impl<'a, 'b> Backup<'a, 'b> { /// /// Will return `Err` if the underlying `sqlite3_backup_init` call returns /// `NULL`. - pub fn new(from: &'a SqliteConnection, - to: &'b mut SqliteConnection) - -> SqliteResult> { + pub fn new(from: &'a Connection, + to: &'b mut Connection) + -> Result> { Backup::new_with_names(from, DatabaseName::Main, to, DatabaseName::Main) } @@ -185,11 +185,11 @@ impl<'a, 'b> Backup<'a, 'b> { /// /// Will return `Err` if the underlying `sqlite3_backup_init` call returns /// `NULL`. - pub fn new_with_names(from: &'a SqliteConnection, + pub fn new_with_names(from: &'a Connection, from_name: DatabaseName, - to: &'b mut SqliteConnection, + to: &'b mut Connection, to_name: DatabaseName) - -> SqliteResult> { + -> Result> { let to_name = try!(to_name.to_cstring()); let from_name = try!(from_name.to_cstring()); @@ -201,7 +201,7 @@ impl<'a, 'b> Backup<'a, 'b> { from.db.borrow_mut().db, from_name.as_ptr()); if b.is_null() { - return Err(SqliteError::from_handle(to_db, ffi::sqlite3_errcode(to_db))); + return Err(Error::from_handle(to_db, ffi::sqlite3_errcode(to_db))); } b }; @@ -235,7 +235,7 @@ impl<'a, 'b> Backup<'a, 'b> { /// an error code other than `DONE`, `OK`, `BUSY`, or `LOCKED`. `BUSY` and /// `LOCKED` are transient errors and are therefore returned as possible /// `Ok` values. - pub fn step(&self, num_pages: c_int) -> SqliteResult { + pub fn step(&self, num_pages: c_int) -> Result { use self::StepResult::{Done, More, Busy, Locked}; let rc = unsafe { ffi::sqlite3_backup_step(self.b, num_pages) }; @@ -245,7 +245,7 @@ impl<'a, 'b> Backup<'a, 'b> { ffi::SQLITE_BUSY => Ok(Busy), ffi::SQLITE_LOCKED => Ok(Locked), rc => { - Err(SqliteError { + Err(Error { code: rc, message: ffi::code_to_str(rc).into(), }) @@ -272,7 +272,7 @@ impl<'a, 'b> Backup<'a, 'b> { pages_per_step: c_int, pause_between_pages: Duration, progress: Option) - -> SqliteResult<()> { + -> Result<()> { use self::StepResult::{Done, More, Busy, Locked}; assert!(pages_per_step > 0, "pages_per_step must be positive"); @@ -298,21 +298,21 @@ impl<'a, 'b> Drop for Backup<'a, 'b> { #[cfg(test)] mod test { - use {SqliteConnection, DatabaseName}; + use {Connection, DatabaseName}; use std::time::Duration; use super::Backup; #[test] #[cfg_attr(rustfmt, rustfmt_skip)] fn test_backup() { - let src = SqliteConnection::open_in_memory().unwrap(); + let src = Connection::open_in_memory().unwrap(); let sql = "BEGIN; CREATE TABLE foo(x INTEGER); INSERT INTO foo VALUES(42); END;"; src.execute_batch(sql).unwrap(); - let mut dst = SqliteConnection::open_in_memory().unwrap(); + let mut dst = Connection::open_in_memory().unwrap(); { let backup = Backup::new(&src, &mut dst).unwrap(); @@ -336,14 +336,14 @@ mod test { #[test] #[cfg_attr(rustfmt, rustfmt_skip)] fn test_backup_temp() { - let src = SqliteConnection::open_in_memory().unwrap(); + let src = Connection::open_in_memory().unwrap(); let sql = "BEGIN; CREATE TEMPORARY TABLE foo(x INTEGER); INSERT INTO foo VALUES(42); END;"; src.execute_batch(sql).unwrap(); - let mut dst = SqliteConnection::open_in_memory().unwrap(); + let mut dst = Connection::open_in_memory().unwrap(); { let backup = Backup::new_with_names(&src, @@ -375,7 +375,7 @@ mod test { #[test] #[cfg_attr(rustfmt, rustfmt_skip)] fn test_backup_attached() { - let src = SqliteConnection::open_in_memory().unwrap(); + let src = Connection::open_in_memory().unwrap(); let sql = "ATTACH DATABASE ':memory:' AS my_attached; BEGIN; CREATE TABLE my_attached.foo(x INTEGER); @@ -383,7 +383,7 @@ mod test { END;"; src.execute_batch(sql).unwrap(); - let mut dst = SqliteConnection::open_in_memory().unwrap(); + let mut dst = Connection::open_in_memory().unwrap(); { let backup = Backup::new_with_names(&src, diff --git a/src/functions.rs b/src/functions.rs index d8df619..502b83a 100644 --- a/src/functions.rs +++ b/src/functions.rs @@ -12,11 +12,11 @@ //! extern crate rusqlite; //! extern crate regex; //! -//! use rusqlite::{SqliteConnection, SqliteError, SqliteResult}; +//! use rusqlite::{Connection, Error, Result}; //! use std::collections::HashMap; //! use regex::Regex; //! -//! fn add_regexp_function(db: &SqliteConnection) -> SqliteResult<()> { +//! fn add_regexp_function(db: &Connection) -> Result<()> { //! let mut cached_regexes = HashMap::new(); //! db.create_scalar_function("regexp", 2, true, move |ctx| { //! let regex_s = try!(ctx.get::(0)); @@ -26,7 +26,7 @@ //! match entry { //! Occupied(occ) => occ.into_mut(), //! Vacant(vac) => { -//! let r = try!(Regex::new(®ex_s).map_err(|e| SqliteError { +//! let r = try!(Regex::new(®ex_s).map_err(|e| Error { //! code: libsqlite3_sys::SQLITE_ERROR, //! message: format!("Invalid regular expression: {}", e), //! })); @@ -41,7 +41,7 @@ //! } //! //! fn main() { -//! let db = SqliteConnection::open_in_memory().unwrap(); +//! let db = Connection::open_in_memory().unwrap(); //! add_regexp_function(&db).unwrap(); //! //! let is_match = db.query_row("SELECT regexp('[aeiou]*', 'aaaaeeeiii')", &[], @@ -65,7 +65,7 @@ pub use ffi::sqlite3_value_numeric_type; use types::Null; -use {SqliteResult, SqliteError, SqliteConnection, str_to_cstring, InnerSqliteConnection}; +use {Result, Error, Connection, str_to_cstring, InnerConnection}; /// A trait for types that can be converted into the result of an SQL function. pub trait ToResult { @@ -165,7 +165,7 @@ impl ToResult for Null { /// A trait for types that can be created from a SQLite function parameter value. pub trait FromValue: Sized { - unsafe fn parameter_value(v: *mut sqlite3_value) -> SqliteResult; + unsafe fn parameter_value(v: *mut sqlite3_value) -> Result; /// FromValue types can implement this method and use sqlite3_value_type to check that /// the type reported by SQLite matches a type suitable for Self. This method is used @@ -180,7 +180,7 @@ pub trait FromValue: Sized { macro_rules! raw_from_impl( ($t:ty, $f:ident, $c:expr) => ( impl FromValue for $t { - unsafe fn parameter_value(v: *mut sqlite3_value) -> SqliteResult<$t> { + unsafe fn parameter_value(v: *mut sqlite3_value) -> Result<$t> { Ok(ffi::$f(v)) } @@ -195,7 +195,7 @@ raw_from_impl!(c_int, sqlite3_value_int, ffi::SQLITE_INTEGER); raw_from_impl!(i64, sqlite3_value_int64, ffi::SQLITE_INTEGER); impl FromValue for bool { - unsafe fn parameter_value(v: *mut sqlite3_value) -> SqliteResult { + unsafe fn parameter_value(v: *mut sqlite3_value) -> Result { match ffi::sqlite3_value_int(v) { 0 => Ok(false), _ => Ok(true), @@ -208,7 +208,7 @@ impl FromValue for bool { } impl FromValue for c_double { - unsafe fn parameter_value(v: *mut sqlite3_value) -> SqliteResult { + unsafe fn parameter_value(v: *mut sqlite3_value) -> Result { Ok(ffi::sqlite3_value_double(v)) } @@ -219,7 +219,7 @@ impl FromValue for c_double { } impl FromValue for String { - unsafe fn parameter_value(v: *mut sqlite3_value) -> SqliteResult { + unsafe fn parameter_value(v: *mut sqlite3_value) -> Result { let c_text = ffi::sqlite3_value_text(v); if c_text.is_null() { Ok("".to_string()) @@ -228,7 +228,7 @@ impl FromValue for String { let utf8_str = str::from_utf8(c_slice); utf8_str.map(|s| s.to_string()) .map_err(|e| { - SqliteError { + Error { code: 0, message: e.to_string(), } @@ -242,7 +242,7 @@ impl FromValue for String { } impl FromValue for Vec { - unsafe fn parameter_value(v: *mut sqlite3_value) -> SqliteResult> { + unsafe fn parameter_value(v: *mut sqlite3_value) -> Result> { use std::slice::from_raw_parts; let c_blob = ffi::sqlite3_value_blob(v); let len = ffi::sqlite3_value_bytes(v); @@ -260,7 +260,7 @@ impl FromValue for Vec { } impl FromValue for Option { - unsafe fn parameter_value(v: *mut sqlite3_value) -> SqliteResult> { + unsafe fn parameter_value(v: *mut sqlite3_value) -> Result> { if sqlite3_value_type(v) == ffi::SQLITE_NULL { Ok(None) } else { @@ -296,13 +296,13 @@ impl<'a> Context<'a> { /// Will panic if `idx` is greater than or equal to `self.len()`. /// /// Will return Err if the underlying SQLite type cannot be converted to a `T`. - pub fn get(&self, idx: usize) -> SqliteResult { + pub fn get(&self, idx: usize) -> Result { let arg = self.args[idx]; unsafe { if T::parameter_has_valid_sqlite_type(arg) { T::parameter_value(arg) } else { - Err(SqliteError { + Err(Error { code: ffi::SQLITE_MISMATCH, message: "Invalid value type".to_string(), }) @@ -341,7 +341,7 @@ impl<'a> Context<'a> { } } -impl SqliteConnection { +impl Connection { /// Attach a user-defined scalar function to this database connection. /// /// `fn_name` is the name the function will be accessible from SQL. @@ -355,9 +355,9 @@ impl SqliteConnection { /// # Example /// /// ```rust - /// # use rusqlite::{SqliteConnection, SqliteResult}; + /// # use rusqlite::{Connection, Result}; /// # type c_double = f64; - /// fn scalar_function_example(db: SqliteConnection) -> SqliteResult<()> { + /// fn scalar_function_example(db: Connection) -> Result<()> { /// try!(db.create_scalar_function("halve", 1, true, |ctx| { /// let value = try!(ctx.get::(0)); /// Ok(value / 2f64) @@ -377,8 +377,8 @@ impl SqliteConnection { n_arg: c_int, deterministic: bool, x_func: F) - -> SqliteResult<()> - where F: FnMut(&Context) -> SqliteResult, + -> Result<()> + where F: FnMut(&Context) -> Result, T: ToResult { self.db.borrow_mut().create_scalar_function(fn_name, n_arg, deterministic, x_func) @@ -392,25 +392,25 @@ impl SqliteConnection { /// # Failure /// /// Will return Err if the function could not be removed. - pub fn remove_function(&self, fn_name: &str, n_arg: c_int) -> SqliteResult<()> { + pub fn remove_function(&self, fn_name: &str, n_arg: c_int) -> Result<()> { self.db.borrow_mut().remove_function(fn_name, n_arg) } } -impl InnerSqliteConnection { +impl InnerConnection { fn create_scalar_function(&mut self, fn_name: &str, n_arg: c_int, deterministic: bool, x_func: F) - -> SqliteResult<()> - where F: FnMut(&Context) -> SqliteResult, + -> Result<()> + where F: FnMut(&Context) -> Result, T: ToResult { extern "C" fn call_boxed_closure(ctx: *mut sqlite3_context, argc: c_int, argv: *mut *mut sqlite3_value) - where F: FnMut(&Context) -> SqliteResult, + where F: FnMut(&Context) -> Result, T: ToResult { unsafe { @@ -452,7 +452,7 @@ impl InnerSqliteConnection { self.decode_result(r) } - fn remove_function(&mut self, fn_name: &str, n_arg: c_int) -> SqliteResult<()> { + fn remove_function(&mut self, fn_name: &str, n_arg: c_int) -> Result<()> { let c_name = try!(str_to_cstring(fn_name)); let r = unsafe { ffi::sqlite3_create_function_v2(self.db(), @@ -477,11 +477,11 @@ mod test { use libc::c_double; use self::regex::Regex; - use {SqliteConnection, SqliteError, SqliteResult}; + use {Connection, Error, Result}; use ffi; use functions::Context; - fn half(ctx: &Context) -> SqliteResult { + fn half(ctx: &Context) -> Result { assert!(ctx.len() == 1, "called with unexpected number of arguments"); let value = try!(ctx.get::(0)); Ok(value / 2f64) @@ -489,7 +489,7 @@ mod test { #[test] fn test_function_half() { - let db = SqliteConnection::open_in_memory().unwrap(); + let db = Connection::open_in_memory().unwrap(); db.create_scalar_function("half", 1, true, half).unwrap(); let result = db.query_row("SELECT half(6)", &[], |r| r.get::(0)); @@ -498,7 +498,7 @@ mod test { #[test] fn test_remove_function() { - let db = SqliteConnection::open_in_memory().unwrap(); + let db = Connection::open_in_memory().unwrap(); db.create_scalar_function("half", 1, true, half).unwrap(); let result = db.query_row("SELECT half(6)", &[], |r| r.get::(0)); assert_eq!(3f64, result.unwrap()); @@ -511,7 +511,7 @@ mod test { // This implementation of a regexp scalar function uses SQLite's auxilliary data // (https://www.sqlite.org/c3ref/get_auxdata.html) to avoid recompiling the regular // expression multiple times within one query. - fn regexp_with_auxilliary(ctx: &Context) -> SqliteResult { + fn regexp_with_auxilliary(ctx: &Context) -> Result { assert!(ctx.len() == 2, "called with unexpected number of arguments"); let saved_re: Option<&Regex> = unsafe { ctx.get_aux(0) }; @@ -519,7 +519,7 @@ mod test { None => { let s = try!(ctx.get::(0)); let r = try!(Regex::new(&s).map_err(|e| { - SqliteError { + Error { code: ffi::SQLITE_ERROR, message: format!("Invalid regular expression: {}", e), } @@ -546,7 +546,7 @@ mod test { #[test] #[cfg_attr(rustfmt, rustfmt_skip)] fn test_function_regexp_with_auxilliary() { - let db = SqliteConnection::open_in_memory().unwrap(); + let db = Connection::open_in_memory().unwrap(); db.execute_batch("BEGIN; CREATE TABLE foo (x string); INSERT INTO foo VALUES ('lisa'); @@ -571,7 +571,7 @@ mod test { #[test] #[cfg_attr(rustfmt, rustfmt_skip)] fn test_function_regexp_with_hashmap_cache() { - let db = SqliteConnection::open_in_memory().unwrap(); + let db = Connection::open_in_memory().unwrap(); db.execute_batch("BEGIN; CREATE TABLE foo (x string); INSERT INTO foo VALUES ('lisa'); @@ -593,7 +593,7 @@ mod test { match entry { Occupied(occ) => occ.into_mut(), Vacant(vac) => { - let r = try!(Regex::new(®ex_s).map_err(|e| SqliteError { + let r = try!(Regex::new(®ex_s).map_err(|e| Error { code: ffi::SQLITE_ERROR, message: format!("Invalid regular expression: {}", e), })); @@ -621,7 +621,7 @@ mod test { #[test] fn test_varargs_function() { - let db = SqliteConnection::open_in_memory().unwrap(); + let db = Connection::open_in_memory().unwrap(); db.create_scalar_function("my_concat", -1, true, |ctx| { let mut ret = String::new(); diff --git a/src/lib.rs b/src/lib.rs index 0af8ff5..67fc19f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,7 +6,7 @@ //! extern crate time; //! //! use time::Timespec; -//! use rusqlite::SqliteConnection; +//! use rusqlite::Connection; //! //! #[derive(Debug)] //! struct Person { @@ -17,7 +17,7 @@ //! } //! //! fn main() { -//! let conn = SqliteConnection::open_in_memory().unwrap(); +//! let conn = Connection::open_in_memory().unwrap(); //! //! conn.execute("CREATE TABLE person ( //! id INTEGER PRIMARY KEY, @@ -68,17 +68,16 @@ use std::error; use std::rc::Rc; use std::cell::{RefCell, Cell}; use std::ffi::{CStr, CString}; +use std::result; use std::str; use libc::{c_int, c_void, c_char}; use types::{ToSql, FromSql}; -pub use transaction::SqliteTransaction; -pub use transaction::{SqliteTransactionBehavior, SqliteTransactionDeferred, -SqliteTransactionImmediate, SqliteTransactionExclusive}; +pub use transaction::{SqliteTransaction, Transaction, TransactionBehavior}; #[cfg(feature = "load_extension")] -pub use load_extension_guard::SqliteLoadExtensionGuard; +pub use load_extension_guard::{SqliteLoadExtensionGuard, LoadExtensionGuard}; pub mod types; mod transaction; @@ -88,8 +87,11 @@ mod named_params; #[cfg(feature = "backup")]pub mod backup; #[cfg(feature = "functions")] pub mod functions; +/// Old name for `Result`. `SqliteResult` is deprecated. +pub type SqliteResult = Result; + /// A typedef of the result returned by many methods. -pub type SqliteResult = Result; +pub type Result = result::Result; unsafe fn errmsg_to_string(errmsg: *const c_char) -> String { let c_slice = CStr::from_ptr(errmsg).to_bytes(); @@ -97,9 +99,12 @@ unsafe fn errmsg_to_string(errmsg: *const c_char) -> String { utf8_str.unwrap_or("Invalid string encoding").to_string() } +/// Old name for `Error`. `SqliteError` is deprecated. +pub type SqliteError = Error; + /// Encompasses an error result from a call to the SQLite C API. #[derive(Debug, PartialEq)] -pub struct SqliteError { +pub struct Error { /// The error code returned by a SQLite C API call. See [SQLite Result /// Codes](http://www.sqlite.org/rescode.html) for details. pub code: c_int, @@ -109,43 +114,43 @@ pub struct SqliteError { pub message: String, } -impl fmt::Display for SqliteError { +impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} (SQLite error {})", self.message, self.code) } } -impl error::Error for SqliteError { +impl error::Error for Error { fn description(&self) -> &str { &self.message } } -impl SqliteError { - fn from_handle(db: *mut ffi::Struct_sqlite3, code: c_int) -> SqliteError { +impl Error { + fn from_handle(db: *mut ffi::Struct_sqlite3, code: c_int) -> Error { let message = if db.is_null() { ffi::code_to_str(code).to_string() } else { unsafe { errmsg_to_string(ffi::sqlite3_errmsg(db)) } }; - SqliteError { + Error { code: code, message: message, } } } -fn str_to_cstring(s: &str) -> SqliteResult { +fn str_to_cstring(s: &str) -> Result { CString::new(s).map_err(|_| { - SqliteError { + Error { code: ffi::SQLITE_MISUSE, 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 { +fn path_to_cstring(p: &Path) -> Result { + let s = try!(p.to_str().ok_or(Error { code: ffi::SQLITE_MISUSE, message: format!("Could not convert path {} to UTF-8 string", p.to_string_lossy()), @@ -169,7 +174,7 @@ pub enum DatabaseName<'a> { // impl to avoid dead code warnings. #[cfg(feature = "backup")] impl<'a> DatabaseName<'a> { - fn to_cstring(self) -> SqliteResult { + fn to_cstring(self) -> Result { use self::DatabaseName::{Main, Temp, Attached}; match self { Main => str_to_cstring("main"), @@ -179,27 +184,30 @@ impl<'a> DatabaseName<'a> { } } +/// Old name for `Connection`. `SqliteConnection` is deprecated. +pub type SqliteConnection = Connection; + /// A connection to a SQLite database. -pub struct SqliteConnection { - db: RefCell, +pub struct Connection { + db: RefCell, path: Option, } -unsafe impl Send for SqliteConnection {} +unsafe impl Send for Connection {} -impl SqliteConnection { +impl Connection { /// Open a new connection to a SQLite database. /// - /// `SqliteConnection::open(path)` is equivalent to `SqliteConnection::open_with_flags(path, + /// `Connection::open(path)` is equivalent to `Connection::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 { + pub fn open>(path: P) -> Result { let flags = Default::default(); - SqliteConnection::open_with_flags(path, flags) + Connection::open_with_flags(path, flags) } /// Open a new connection to an in-memory SQLite database. @@ -207,9 +215,9 @@ impl SqliteConnection { /// # Failure /// /// Will return `Err` if the underlying SQLite open call fails. - pub fn open_in_memory() -> SqliteResult { + pub fn open_in_memory() -> Result { let flags = Default::default(); - SqliteConnection::open_in_memory_with_flags(flags) + Connection::open_in_memory_with_flags(flags) } /// Open a new connection to a SQLite database. @@ -222,11 +230,11 @@ impl SqliteConnection { /// 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 { + flags: OpenFlags) + -> Result { let c_path = try!(path_to_cstring(path.as_ref())); - InnerSqliteConnection::open_with_flags(&c_path, flags).map(|db| { - SqliteConnection { + InnerConnection::open_with_flags(&c_path, flags).map(|db| { + Connection { db: RefCell::new(db), path: Some(path.as_ref().to_path_buf()), } @@ -241,10 +249,10 @@ impl SqliteConnection { /// # Failure /// /// Will return `Err` if the underlying SQLite open call fails. - pub fn open_in_memory_with_flags(flags: SqliteOpenFlags) -> SqliteResult { + pub fn open_in_memory_with_flags(flags: OpenFlags) -> Result { let c_memory = try!(str_to_cstring(":memory:")); - InnerSqliteConnection::open_with_flags(&c_memory, flags).map(|db| { - SqliteConnection { + InnerConnection::open_with_flags(&c_memory, flags).map(|db| { + Connection { db: RefCell::new(db), path: None, } @@ -259,10 +267,10 @@ impl SqliteConnection { /// ## Example /// /// ```rust,no_run - /// # use rusqlite::{SqliteConnection, SqliteResult}; - /// # fn do_queries_part_1(conn: &SqliteConnection) -> SqliteResult<()> { Ok(()) } - /// # fn do_queries_part_2(conn: &SqliteConnection) -> SqliteResult<()> { Ok(()) } - /// fn perform_queries(conn: &SqliteConnection) -> SqliteResult<()> { + /// # use rusqlite::{Connection, Result}; + /// # fn do_queries_part_1(conn: &Connection) -> Result<()> { Ok(()) } + /// # fn do_queries_part_2(conn: &Connection) -> Result<()> { Ok(()) } + /// fn perform_queries(conn: &Connection) -> Result<()> { /// let tx = try!(conn.transaction()); /// /// try!(do_queries_part_1(conn)); // tx causes rollback if this fails @@ -275,8 +283,8 @@ impl SqliteConnection { /// # Failure /// /// Will return `Err` if the underlying SQLite call fails. - pub fn transaction<'a>(&'a self) -> SqliteResult> { - SqliteTransaction::new(self, SqliteTransactionDeferred) + pub fn transaction<'a>(&'a self) -> Result> { + Transaction::new(self, TransactionBehavior::Deferred) } /// Begin a new transaction with a specified behavior. @@ -287,9 +295,9 @@ impl SqliteConnection { /// /// Will return `Err` if the underlying SQLite call fails. pub fn transaction_with_behavior<'a>(&'a self, - behavior: SqliteTransactionBehavior) - -> SqliteResult> { - SqliteTransaction::new(self, behavior) + behavior: TransactionBehavior) + -> Result> { + Transaction::new(self, behavior) } /// Convenience method to run multiple SQL statements (that cannot take any parameters). @@ -299,8 +307,8 @@ impl SqliteConnection { /// ## Example /// /// ```rust,no_run - /// # use rusqlite::{SqliteConnection, SqliteResult}; - /// fn create_tables(conn: &SqliteConnection) -> SqliteResult<()> { + /// # use rusqlite::{Connection, Result}; + /// fn create_tables(conn: &Connection) -> Result<()> { /// conn.execute_batch("BEGIN; /// CREATE TABLE foo(x INTEGER); /// CREATE TABLE bar(y TEXT); @@ -312,7 +320,7 @@ impl SqliteConnection { /// /// 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<()> { + pub fn execute_batch(&self, sql: &str) -> Result<()> { self.db.borrow_mut().execute_batch(sql) } @@ -324,8 +332,8 @@ impl SqliteConnection { /// ## Example /// /// ```rust,no_run - /// # use rusqlite::{SqliteConnection}; - /// fn update_rows(conn: &SqliteConnection) { + /// # use rusqlite::{Connection}; + /// fn update_rows(conn: &Connection) { /// match conn.execute("UPDATE foo SET bar = 'baz' WHERE qux = ?", &[&1i32]) { /// Ok(updated) => println!("{} rows were updated", updated), /// Err(err) => println!("update failed: {}", err), @@ -337,7 +345,7 @@ impl SqliteConnection { /// /// 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 { + pub fn execute(&self, sql: &str, params: &[&ToSql]) -> Result { self.prepare(sql).and_then(|mut stmt| stmt.execute(params)) } @@ -354,8 +362,8 @@ impl SqliteConnection { /// ## Example /// /// ```rust,no_run - /// # use rusqlite::{SqliteResult,SqliteConnection}; - /// fn preferred_locale(conn: &SqliteConnection) -> SqliteResult { + /// # use rusqlite::{Result,Connection}; + /// fn preferred_locale(conn: &Connection) -> Result { /// conn.query_row("SELECT value FROM preferences WHERE name='locale'", &[], |row| { /// row.get(0) /// }) @@ -368,8 +376,8 @@ impl SqliteConnection { /// /// 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 + pub fn query_row(&self, sql: &str, params: &[&ToSql], f: F) -> Result + where F: FnOnce(Row) -> T { let mut stmt = try!(self.prepare(sql)); let mut rows = try!(stmt.query(params)); @@ -379,13 +387,13 @@ 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`. + /// The `Result` type of `f` must implement `std::convert::From`. /// /// ## Example /// /// ```rust,no_run - /// # use rusqlite::{SqliteResult,SqliteConnection}; - /// fn preferred_locale(conn: &SqliteConnection) -> SqliteResult { + /// # use rusqlite::{Result,Connection}; + /// fn preferred_locale(conn: &Connection) -> Result { /// conn.query_row_and_then("SELECT value FROM preferences WHERE name='locale'", &[], |row| { /// row.get_checked(0) /// }) @@ -398,9 +406,9 @@ impl SqliteConnection { /// /// 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 + pub fn query_row_and_then(&self, sql: &str, params: &[&ToSql], f: F) -> result::Result + where F: FnOnce(Row) -> result::Result, + E: convert::From { let mut stmt = try!(self.prepare(sql)); let mut rows = try!(stmt.query(params)); @@ -413,8 +421,8 @@ impl SqliteConnection { /// ## Example /// /// ```rust,no_run - /// # use rusqlite::{SqliteResult,SqliteConnection}; - /// fn preferred_locale(conn: &SqliteConnection) -> SqliteResult { + /// # use rusqlite::{Result,Connection}; + /// fn preferred_locale(conn: &Connection) -> Result { /// conn.query_row_safe("SELECT value FROM preferences WHERE name='locale'", &[], |row| { /// row.get(0) /// }) @@ -427,8 +435,8 @@ impl SqliteConnection { /// /// This method should be considered deprecated. Use `query_row` instead, which now /// does exactly the same thing. - pub fn query_row_safe(&self, sql: &str, params: &[&ToSql], f: F) -> SqliteResult - where F: FnOnce(SqliteRow) -> T + pub fn query_row_safe(&self, sql: &str, params: &[&ToSql], f: F) -> Result + where F: FnOnce(Row) -> T { self.query_row(sql, params, f) } @@ -438,8 +446,8 @@ impl SqliteConnection { /// ## Example /// /// ```rust,no_run - /// # use rusqlite::{SqliteConnection, SqliteResult}; - /// fn insert_new_people(conn: &SqliteConnection) -> SqliteResult<()> { + /// # use rusqlite::{Connection, Result}; + /// fn insert_new_people(conn: &Connection) -> Result<()> { /// let mut stmt = try!(conn.prepare("INSERT INTO People (name) VALUES (?)")); /// try!(stmt.execute(&[&"Joe Smith"])); /// try!(stmt.execute(&[&"Bob Jones"])); @@ -451,32 +459,32 @@ impl SqliteConnection { /// /// 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> { + pub fn prepare<'a>(&'a self, sql: &str) -> Result> { self.db.borrow_mut().prepare(self, sql) } /// Close the SQLite connection. /// - /// This is functionally equivalent to the `Drop` implementation for `SqliteConnection` except + /// This is functionally equivalent to the `Drop` implementation for `Connection` 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<()> { + pub fn close(self) -> Result<()> { let mut db = self.db.borrow_mut(); db.close() } - /// Enable loading of SQLite extensions. Strongly consider using `SqliteLoadExtensionGuard` + /// Enable loading of SQLite extensions. Strongly consider using `LoadExtensionGuard` /// instead of this function. /// /// ## Example /// /// ```rust,no_run - /// # use rusqlite::{SqliteConnection, SqliteResult}; + /// # use rusqlite::{Connection, Result}; /// # use std::path::{Path}; - /// fn load_my_extension(conn: &SqliteConnection) -> SqliteResult<()> { + /// fn load_my_extension(conn: &Connection) -> Result<()> { /// try!(conn.load_extension_enable()); /// try!(conn.load_extension(Path::new("my_sqlite_extension"), None)); /// conn.load_extension_disable() @@ -487,7 +495,7 @@ impl SqliteConnection { /// /// Will return `Err` if the underlying SQLite call fails. #[cfg(feature = "load_extension")] - pub fn load_extension_enable(&self) -> SqliteResult<()> { + pub fn load_extension_enable(&self) -> Result<()> { self.db.borrow_mut().enable_load_extension(1) } @@ -499,7 +507,7 @@ impl SqliteConnection { /// /// Will return `Err` if the underlying SQLite call fails. #[cfg(feature = "load_extension")] - pub fn load_extension_disable(&self) -> SqliteResult<()> { + pub fn load_extension_disable(&self) -> Result<()> { self.db.borrow_mut().enable_load_extension(0) } @@ -513,10 +521,10 @@ impl SqliteConnection { /// ## Example /// /// ```rust,no_run - /// # use rusqlite::{SqliteConnection, SqliteResult, SqliteLoadExtensionGuard}; + /// # use rusqlite::{Connection, Result, LoadExtensionGuard}; /// # use std::path::{Path}; - /// fn load_my_extension(conn: &SqliteConnection) -> SqliteResult<()> { - /// let _guard = try!(SqliteLoadExtensionGuard::new(conn)); + /// fn load_my_extension(conn: &Connection) -> Result<()> { + /// let _guard = try!(LoadExtensionGuard::new(conn)); /// /// conn.load_extension("my_sqlite_extension", None) /// } @@ -529,11 +537,11 @@ impl SqliteConnection { pub fn load_extension>(&self, dylib_path: P, entry_point: Option<&str>) - -> SqliteResult<()> { + -> Result<()> { self.db.borrow_mut().load_extension(dylib_path.as_ref(), entry_point) } - fn decode_result(&self, code: c_int) -> SqliteResult<()> { + fn decode_result(&self, code: c_int) -> Result<()> { self.db.borrow_mut().decode_result(code) } @@ -542,23 +550,26 @@ impl SqliteConnection { } } -impl fmt::Debug for SqliteConnection { +impl fmt::Debug for Connection { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_struct("SqliteConnection") + f.debug_struct("Connection") .field("path", &self.path) .finish() } } -struct InnerSqliteConnection { +struct InnerConnection { db: *mut ffi::Struct_sqlite3, } +/// Old name for `OpenFlags`. `SqliteOpenFlags` is deprecated. +pub type SqliteOpenFlags = OpenFlags; + bitflags! { #[doc = "Flags for opening SQLite database connections."] #[doc = "See [sqlite3_open_v2](http://www.sqlite.org/c3ref/open.html) for details."] #[repr(C)] - flags SqliteOpenFlags: c_int { + flags OpenFlags: c_int { const SQLITE_OPEN_READ_ONLY = 0x00000001, const SQLITE_OPEN_READ_WRITE = 0x00000002, const SQLITE_OPEN_CREATE = 0x00000004, @@ -571,27 +582,27 @@ bitflags! { } } -impl Default for SqliteOpenFlags { - fn default() -> SqliteOpenFlags { +impl Default for OpenFlags { + fn default() -> OpenFlags { SQLITE_OPEN_READ_WRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NO_MUTEX | SQLITE_OPEN_URI } } -impl InnerSqliteConnection { +impl InnerConnection { fn open_with_flags(c_path: &CString, - flags: SqliteOpenFlags) - -> SqliteResult { + flags: OpenFlags) + -> Result { unsafe { 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() { - SqliteError { + Error { code: r, message: ffi::code_to_str(r).to_string(), } } else { - let e = SqliteError::from_handle(db, r); + let e = Error::from_handle(db, r); ffi::sqlite3_close(db); e }; @@ -600,11 +611,11 @@ impl InnerSqliteConnection { } let r = ffi::sqlite3_busy_timeout(db, 5000); if r != ffi::SQLITE_OK { - let e = SqliteError::from_handle(db, r); + let e = Error::from_handle(db, r); ffi::sqlite3_close(db); return Err(e); } - Ok(InnerSqliteConnection { db: db }) + Ok(InnerConnection { db: db }) } } @@ -612,31 +623,31 @@ impl InnerSqliteConnection { self.db } - fn decode_result(&mut self, code: c_int) -> SqliteResult<()> { + fn decode_result(&mut self, code: c_int) -> Result<()> { if code == ffi::SQLITE_OK { Ok(()) } else { - Err(SqliteError::from_handle(self.db(), code)) + Err(Error::from_handle(self.db(), code)) } } unsafe fn decode_result_with_errmsg(&self, code: c_int, errmsg: *mut c_char) - -> SqliteResult<()> { + -> Result<()> { if code == ffi::SQLITE_OK { Ok(()) } else { let message = errmsg_to_string(&*errmsg); ffi::sqlite3_free(errmsg as *mut c_void); - Err(SqliteError { + Err(Error { code: code, message: message, }) } } - fn close(&mut self) -> SqliteResult<()> { + fn close(&mut self) -> Result<()> { unsafe { let r = ffi::sqlite3_close(self.db()); self.db = ptr::null_mut(); @@ -644,7 +655,7 @@ impl InnerSqliteConnection { } } - fn execute_batch(&mut self, sql: &str) -> SqliteResult<()> { + fn execute_batch(&mut self, sql: &str) -> Result<()> { let c_sql = try!(str_to_cstring(sql)); unsafe { let mut errmsg: *mut c_char = mem::uninitialized(); @@ -658,13 +669,13 @@ impl InnerSqliteConnection { } #[cfg(feature = "load_extension")] - fn enable_load_extension(&mut self, onoff: c_int) -> SqliteResult<()> { + fn enable_load_extension(&mut self, onoff: c_int) -> Result<()> { let r = unsafe { ffi::sqlite3_enable_load_extension(self.db, onoff) }; self.decode_result(r) } #[cfg(feature = "load_extension")] - fn load_extension(&self, dylib_path: &Path, entry_point: Option<&str>) -> SqliteResult<()> { + fn load_extension(&self, dylib_path: &Path, entry_point: Option<&str>) -> Result<()> { let dylib_str = try!(path_to_cstring(dylib_path)); unsafe { let mut errmsg: *mut c_char = mem::uninitialized(); @@ -686,11 +697,11 @@ impl InnerSqliteConnection { } fn prepare<'a>(&mut self, - conn: &'a SqliteConnection, + conn: &'a Connection, sql: &str) - -> SqliteResult> { + -> Result> { if sql.len() >= ::std::i32::MAX as usize { - return Err(SqliteError { + return Err(Error { code: ffi::SQLITE_TOOBIG, message: "statement too long".to_string(), }); @@ -705,7 +716,7 @@ impl InnerSqliteConnection { &mut c_stmt, ptr::null_mut()) }; - self.decode_result(r).map(|_| SqliteStatement::new(conn, c_stmt)) + self.decode_result(r).map(|_| Statement::new(conn, c_stmt)) } fn changes(&mut self) -> c_int { @@ -713,24 +724,27 @@ impl InnerSqliteConnection { } } -impl Drop for InnerSqliteConnection { +impl Drop for InnerConnection { #[allow(unused_must_use)] fn drop(&mut self) { self.close(); } } +/// Old name for `Statement`. `SqliteStatement` is deprecated. +pub type SqliteStatement<'conn> = Statement<'conn>; + /// A prepared statement. -pub struct SqliteStatement<'conn> { - conn: &'conn SqliteConnection, +pub struct Statement<'conn> { + conn: &'conn Connection, 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 { +impl<'conn> Statement<'conn> { + fn new(conn: &Connection, stmt: *mut ffi::sqlite3_stmt) -> Statement { + Statement { conn: conn, stmt: stmt, needs_reset: false, @@ -758,8 +772,8 @@ impl<'conn> SqliteStatement<'conn> { /// ## Example /// /// ```rust,no_run - /// # use rusqlite::{SqliteConnection, SqliteResult}; - /// fn update_rows(conn: &SqliteConnection) -> SqliteResult<()> { + /// # use rusqlite::{Connection, Result}; + /// fn update_rows(conn: &Connection) -> Result<()> { /// let mut stmt = try!(conn.prepare("UPDATE foo SET bar = 'baz' WHERE qux = ?")); /// /// try!(stmt.execute(&[&1i32])); @@ -773,20 +787,20 @@ impl<'conn> SqliteStatement<'conn> { /// /// 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 { + pub fn execute(&mut self, params: &[&ToSql]) -> Result { unsafe { try!(self.bind_parameters(params)); self.execute_() } } - unsafe fn execute_(&mut self) -> SqliteResult { + unsafe fn execute_(&mut self) -> Result { let r = ffi::sqlite3_step(self.stmt); ffi::sqlite3_reset(self.stmt); match r { ffi::SQLITE_DONE => { if self.column_count != 0 { - Err(SqliteError { + Err(Error { code: ffi::SQLITE_MISUSE, message: "Unexpected column count - did you mean to call query?" .to_string(), @@ -796,7 +810,7 @@ impl<'conn> SqliteStatement<'conn> { } } ffi::SQLITE_ROW => { - Err(SqliteError { + Err(Error { code: r, message: "Unexpected row result - did you mean to call query?".to_string(), }) @@ -810,8 +824,8 @@ impl<'conn> SqliteStatement<'conn> { /// ## Example /// /// ```rust,no_run - /// # use rusqlite::{SqliteConnection, SqliteResult}; - /// fn get_names(conn: &SqliteConnection) -> SqliteResult> { + /// # use rusqlite::{Connection, Result}; + /// fn get_names(conn: &Connection) -> Result> { /// let mut stmt = try!(conn.prepare("SELECT name FROM people")); /// let mut rows = try!(stmt.query(&[])); /// @@ -828,7 +842,7 @@ impl<'conn> SqliteStatement<'conn> { /// # Failure /// /// Will return `Err` if binding parameters fails. - pub fn query<'a>(&'a mut self, params: &[&ToSql]) -> SqliteResult> { + pub fn query<'a>(&'a mut self, params: &[&ToSql]) -> Result> { self.reset_if_needed(); unsafe { @@ -836,7 +850,7 @@ impl<'conn> SqliteStatement<'conn> { } self.needs_reset = true; - Ok(SqliteRows::new(self)) + Ok(Rows::new(self)) } /// Executes the prepared statement and maps a function over the resulting @@ -851,8 +865,8 @@ impl<'conn> SqliteStatement<'conn> { pub fn query_map<'a, T, F>(&'a mut self, params: &[&ToSql], f: F) - -> SqliteResult> - where F: FnMut(&SqliteRow) -> T + -> Result> + where F: FnMut(&Row) -> T { let row_iter = try!(self.query(params)); @@ -864,7 +878,7 @@ 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). + /// `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. @@ -875,9 +889,9 @@ impl<'conn> SqliteStatement<'conn> { pub fn query_and_then<'a, T, E, F>(&'a mut self, params: &[&ToSql], f: F) - -> SqliteResult> - where E: convert::From, - F: FnMut(&SqliteRow) -> Result + -> Result> + where E: convert::From, + F: FnMut(&Row) -> result::Result { let row_iter = try!(self.query(params)); @@ -895,11 +909,11 @@ impl<'conn> SqliteStatement<'conn> { /// # Failure /// /// Will return `Err` if the underlying SQLite call fails. - pub fn finalize(mut self) -> SqliteResult<()> { + pub fn finalize(mut self) -> Result<()> { self.finalize_() } - unsafe fn bind_parameters(&mut self, params: &[&ToSql]) -> SqliteResult<()> { + unsafe fn bind_parameters(&mut self, params: &[&ToSql]) -> Result<()> { assert!(params.len() as c_int == ffi::sqlite3_bind_parameter_count(self.stmt), "incorrect number of parameters to query(): expected {}, got {}", ffi::sqlite3_bind_parameter_count(self.stmt), @@ -921,20 +935,20 @@ impl<'conn> SqliteStatement<'conn> { } } - fn finalize_(&mut self) -> SqliteResult<()> { + fn finalize_(&mut self) -> Result<()> { let r = unsafe { ffi::sqlite3_finalize(self.stmt) }; self.stmt = ptr::null_mut(); self.conn.decode_result(r) } } -impl<'conn> fmt::Debug for SqliteStatement<'conn> { +impl<'conn> fmt::Debug for Statement<'conn> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let sql = unsafe { let c_slice = CStr::from_ptr(ffi::sqlite3_sql(self.stmt)).to_bytes(); str::from_utf8(c_slice) }; - f.debug_struct("SqliteStatement") + f.debug_struct("Statement") .field("conn", self.conn) .field("stmt", &self.stmt) .field("sql", &sql) @@ -942,7 +956,7 @@ impl<'conn> fmt::Debug for SqliteStatement<'conn> { } } -impl<'conn> Drop for SqliteStatement<'conn> { +impl<'conn> Drop for Statement<'conn> { #[allow(unused_must_use)] fn drop(&mut self) { self.finalize_(); @@ -951,31 +965,31 @@ impl<'conn> Drop for SqliteStatement<'conn> { /// An iterator over the mapped resulting rows of a query. pub struct MappedRows<'stmt, F> { - rows: SqliteRows<'stmt>, + rows: Rows<'stmt>, map: F, } -impl<'stmt, T, F> Iterator for MappedRows<'stmt, F> where F: FnMut(&SqliteRow) -> T +impl<'stmt, T, F> Iterator for MappedRows<'stmt, F> where F: FnMut(&Row) -> T { - type Item = SqliteResult; + type Item = Result; - fn next(&mut self) -> Option> { + fn next(&mut self) -> Option> { self.rows.next().map(|row_result| row_result.map(|row| (self.map)(&row))) } } /// An iterator over the mapped resulting rows of a query, with an Error type -/// unifying with SqliteError. +/// unifying with Error. pub struct AndThenRows<'stmt, F> { - rows: SqliteRows<'stmt>, + rows: Rows<'stmt>, map: F, } impl<'stmt, T, E, F> Iterator for AndThenRows<'stmt, F> -where E: convert::From, - F: FnMut(&SqliteRow) -> Result +where E: convert::From, + F: FnMut(&Row) -> result::Result { - type Item = Result; + type Item = result::Result; fn next(&mut self) -> Option { self.rows.next().map(|row_result| { @@ -985,17 +999,20 @@ where E: convert::From, } } +/// Old name for `Rows`. `SqliteRows` is deprecated. +pub type SqliteRows<'stmt> = Rows<'stmt>; + /// An iterator over the resulting rows of a query. /// /// ## Warning /// /// Due to the way SQLite returns result rows of a query, it is not safe to attempt to get values -/// from a row after it has become stale (i.e., `next()` has been called again on the `SqliteRows` +/// from a row after it has become stale (i.e., `next()` has been called again on the `Rows` /// iterator). For example: /// /// ```rust,no_run -/// # use rusqlite::{SqliteConnection, SqliteResult}; -/// fn bad_function_will_panic(conn: &SqliteConnection) -> SqliteResult { +/// # use rusqlite::{Connection, Result}; +/// fn bad_function_will_panic(conn: &Connection) -> Result { /// let mut stmt = try!(conn.prepare("SELECT id FROM my_table")); /// let mut rows = try!(stmt.query(&[])); /// @@ -1020,26 +1037,26 @@ where E: convert::From, /// no longer implement `Iterator`, and therefore you would lose access to the majority of /// functions which are useful (such as support for `for ... in ...` looping, `map`, `filter`, /// etc.). -pub struct SqliteRows<'stmt> { - stmt: &'stmt SqliteStatement<'stmt>, +pub struct Rows<'stmt> { + stmt: &'stmt Statement<'stmt>, current_row: Rc>, failed: bool, } -impl<'stmt> SqliteRows<'stmt> { - fn new(stmt: &'stmt SqliteStatement<'stmt>) -> SqliteRows<'stmt> { - SqliteRows { +impl<'stmt> Rows<'stmt> { + fn new(stmt: &'stmt Statement<'stmt>) -> Rows<'stmt> { + Rows { stmt: stmt, current_row: Rc::new(Cell::new(0)), failed: false, } } - fn get_expected_row(&mut self) -> SqliteResult> { + fn get_expected_row(&mut self) -> Result> { match self.next() { Some(row) => row, None => { - Err(SqliteError { + Err(Error { code: ffi::SQLITE_NOTICE, message: "Query did not return a row".to_string(), }) @@ -1048,10 +1065,10 @@ impl<'stmt> SqliteRows<'stmt> { } } -impl<'stmt> Iterator for SqliteRows<'stmt> { - type Item = SqliteResult>; +impl<'stmt> Iterator for Rows<'stmt> { + type Item = Result>; - fn next(&mut self) -> Option>> { + fn next(&mut self) -> Option>> { if self.failed { return None; } @@ -1059,7 +1076,7 @@ impl<'stmt> Iterator for SqliteRows<'stmt> { ffi::SQLITE_ROW => { let current_row = self.current_row.get() + 1; self.current_row.set(current_row); - Some(Ok(SqliteRow { + Some(Ok(Row { stmt: self.stmt, current_row: self.current_row.clone(), row_idx: current_row, @@ -1074,24 +1091,27 @@ impl<'stmt> Iterator for SqliteRows<'stmt> { } } +/// Old name for `Row`. `SqliteRow` is deprecated. +pub type SqliteRow<'stmt> = Row<'stmt>; + /// A single result row of a query. -pub struct SqliteRow<'stmt> { - stmt: &'stmt SqliteStatement<'stmt>, +pub struct Row<'stmt> { + stmt: &'stmt Statement<'stmt>, current_row: Rc>, row_idx: c_int, } -impl<'stmt> SqliteRow<'stmt> { +impl<'stmt> Row<'stmt> { /// Get the value of a particular column of the result row. /// - /// Note that `SqliteRow` can panic at runtime if you use it incorrectly. When you are + /// Note that `Row` can panic at runtime if you use it incorrectly. When you are /// retrieving the rows of a query, a row becomes stale once you have requested the next row, /// and the values can no longer be retrieved. In general (when using looping over the rows, /// for example) this isn't an issue, but it means you cannot do something like this: /// /// ```rust,no_run - /// # use rusqlite::{SqliteConnection, SqliteResult}; - /// fn bad_function_will_panic(conn: &SqliteConnection) -> SqliteResult { + /// # use rusqlite::{Connection, Result}; + /// fn bad_function_will_panic(conn: &Connection) -> Result { /// let mut stmt = try!(conn.prepare("SELECT id FROM my_table")); /// let mut rows = try!(stmt.query(&[])); /// @@ -1118,21 +1138,21 @@ impl<'stmt> SqliteRow<'stmt> { /// /// ## Failure /// - /// Returns a `SQLITE_MISMATCH`-coded `SqliteError` if the underlying SQLite column + /// Returns a `SQLITE_MISMATCH`-coded `Error` if the underlying SQLite column /// type is not a valid type as a source for `T`. /// - /// Returns a `SQLITE_MISUSE`-coded `SqliteError` if `idx` is outside the valid column range + /// Returns a `SQLITE_MISUSE`-coded `Error` 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 { + pub fn get_checked(&self, idx: c_int) -> Result { if self.row_idx != self.current_row.get() { - return Err(SqliteError { + return Err(Error { code: ffi::SQLITE_MISUSE, message: "Cannot get values from a row after advancing to next row".to_string(), }); } unsafe { if idx < 0 || idx >= self.stmt.column_count { - return Err(SqliteError { + return Err(Error { code: ffi::SQLITE_MISUSE, message: "Invalid column index".to_string(), }); @@ -1141,7 +1161,7 @@ impl<'stmt> SqliteRow<'stmt> { if T::column_has_valid_sqlite_type(self.stmt.stmt, idx) { FromSql::column_result(self.stmt.stmt, idx) } else { - Err(SqliteError { + Err(Error { code: ffi::SQLITE_MISMATCH, message: "Invalid column type".to_string(), }) @@ -1164,11 +1184,11 @@ mod test { // that those types are `Send`. #[allow(dead_code, unconditional_recursion)] fn ensure_send() { - ensure_send::(); + ensure_send::(); } - pub fn checked_memory_handle() -> SqliteConnection { - SqliteConnection::open_in_memory().unwrap() + pub fn checked_memory_handle() -> Connection { + Connection::open_in_memory().unwrap() } #[test] @@ -1178,7 +1198,7 @@ mod test { let path = temp_dir.path().join("test.db3"); { - let db = SqliteConnection::open(&path).unwrap(); + let db = Connection::open(&path).unwrap(); let sql = "BEGIN; CREATE TABLE foo(x INTEGER); INSERT INTO foo VALUES(42); @@ -1187,7 +1207,7 @@ mod test { } let path_string = path.to_str().unwrap(); - let db = SqliteConnection::open(&path_string).unwrap(); + let db = Connection::open(&path_string).unwrap(); let the_answer = db.query_row("SELECT x FROM foo", &[], |r| r.get::(0)); assert_eq!(42i64, the_answer.unwrap()); @@ -1195,7 +1215,7 @@ mod test { #[test] fn test_open() { - assert!(SqliteConnection::open_in_memory().is_ok()); + assert!(Connection::open_in_memory().is_ok()); let db = checked_memory_handle(); assert!(db.close().is_ok()); @@ -1203,11 +1223,11 @@ mod test { #[test] fn test_open_with_flags() { - for bad_flags in [SqliteOpenFlags::empty(), + for bad_flags in [OpenFlags::empty(), SQLITE_OPEN_READ_ONLY | SQLITE_OPEN_READ_WRITE, SQLITE_OPEN_READ_ONLY | SQLITE_OPEN_CREATE] .iter() { - assert!(SqliteConnection::open_in_memory_with_flags(*bad_flags).is_err()); + assert!(Connection::open_in_memory_with_flags(*bad_flags).is_err()); } } @@ -1234,10 +1254,10 @@ mod test { let db = checked_memory_handle(); db.execute_batch("CREATE TABLE foo(x INTEGER)").unwrap(); - assert_eq!(db.execute("INSERT INTO foo(x) VALUES (?)", &[&1i32]).unwrap(), - 1); - assert_eq!(db.execute("INSERT INTO foo(x) VALUES (?)", &[&2i32]).unwrap(), - 1); + assert_eq!(1, + db.execute("INSERT INTO foo(x) VALUES (?)", &[&1i32]).unwrap()); + assert_eq!(1, + db.execute("INSERT INTO foo(x) VALUES (?)", &[&2i32]).unwrap()); assert_eq!(3i32, db.query_row("SELECT SUM(x) FROM foo", &[], |r| r.get(0)).unwrap()); @@ -1322,7 +1342,7 @@ mod test { 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_map(&[], |row| row.get(1)) + let results: Result> = query.query_map(&[], |row| row.get(1)) .unwrap() .collect(); @@ -1415,11 +1435,11 @@ mod test { #[derive(Debug, PartialEq)] enum CustomError { SomeError, - Sqlite(SqliteError), + Sqlite(Error), } impl fmt::Display for CustomError { - fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + fn fmt(&self, f: &mut fmt::Formatter) -> ::std::result::Result<(), fmt::Error> { match *self { CustomError::SomeError => write!(f, "{}", self.description()), CustomError::Sqlite(ref se) => write!(f, "{}: {}", self.description(), se), @@ -1439,13 +1459,13 @@ mod test { } } - impl From for CustomError { - fn from(se: SqliteError) -> CustomError { + impl From for CustomError { + fn from(se: Error) -> CustomError { CustomError::Sqlite(se) } } - type CustomResult = Result; + type CustomResult = ::std::result::Result; #[test] #[cfg_attr(rustfmt, rustfmt_skip)] @@ -1461,7 +1481,7 @@ mod test { 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(&[], + let results: Result> = query.query_and_then(&[], |row| row.get_checked(1)) .unwrap() .collect(); @@ -1483,24 +1503,24 @@ mod test { 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(&[], + let bad_type: Result> = query.query_and_then(&[], |row| row.get_checked(1)) .unwrap() .collect(); assert_eq!(bad_type, - Err(SqliteError { + Err(Error { code: ffi::SQLITE_MISMATCH, message: "Invalid column type".to_owned(), })); - let bad_idx: SqliteResult> = query.query_and_then(&[], + let bad_idx: Result> = query.query_and_then(&[], |row| row.get_checked(3)) .unwrap() .collect(); assert_eq!(bad_idx, - Err(SqliteError { + Err(Error { code: ffi::SQLITE_MISUSE, message: "Invalid column index".to_owned(), })); @@ -1552,7 +1572,7 @@ mod test { .collect(); assert_eq!(bad_type, - Err(CustomError::Sqlite(SqliteError { + Err(CustomError::Sqlite(Error { code: ffi::SQLITE_MISMATCH, message: "Invalid column type".to_owned(), }))); @@ -1565,7 +1585,7 @@ mod test { .collect(); assert_eq!(bad_idx, - Err(CustomError::Sqlite(SqliteError { + Err(CustomError::Sqlite(Error { code: ffi::SQLITE_MISUSE, message: "Invalid column index".to_owned(), }))); @@ -1613,7 +1633,7 @@ mod test { }); assert_eq!(bad_type, - Err(CustomError::Sqlite(SqliteError { + Err(CustomError::Sqlite(Error { code: ffi::SQLITE_MISMATCH, message: "Invalid column type".to_owned(), }))); @@ -1623,7 +1643,7 @@ mod test { }); assert_eq!(bad_idx, - Err(CustomError::Sqlite(SqliteError { + Err(CustomError::Sqlite(Error { code: ffi::SQLITE_MISUSE, message: "Invalid column index".to_owned(), }))); diff --git a/src/load_extension_guard.rs b/src/load_extension_guard.rs index ecc93e5..7a02db4 100644 --- a/src/load_extension_guard.rs +++ b/src/load_extension_guard.rs @@ -1,32 +1,35 @@ -use {SqliteResult, SqliteConnection}; +use {Result, Connection}; + +/// Old name for `LoadExtensionGuard`. `SqliteLoadExtensionGuard` is deprecated. +pub type SqliteLoadExtensionGuard<'conn> = LoadExtensionGuard<'conn>; /// RAII guard temporarily enabling SQLite extensions to be loaded. /// /// ## Example /// /// ```rust,no_run -/// # use rusqlite::{SqliteConnection, SqliteResult, SqliteLoadExtensionGuard}; +/// # use rusqlite::{Connection, Result, LoadExtensionGuard}; /// # use std::path::{Path}; -/// fn load_my_extension(conn: &SqliteConnection) -> SqliteResult<()> { -/// let _guard = try!(SqliteLoadExtensionGuard::new(conn)); +/// fn load_my_extension(conn: &Connection) -> Result<()> { +/// let _guard = try!(LoadExtensionGuard::new(conn)); /// /// conn.load_extension(Path::new("my_sqlite_extension"), None) /// } /// ``` -pub struct SqliteLoadExtensionGuard<'conn> { - conn: &'conn SqliteConnection, +pub struct LoadExtensionGuard<'conn> { + conn: &'conn Connection, } -impl<'conn> SqliteLoadExtensionGuard<'conn> { +impl<'conn> LoadExtensionGuard<'conn> { /// Attempt to enable loading extensions. Loading extensions will be disabled when this /// guard goes out of scope. Cannot be meaningfully nested. - pub fn new(conn: &SqliteConnection) -> SqliteResult { - conn.load_extension_enable().map(|_| SqliteLoadExtensionGuard { conn: conn }) + pub fn new(conn: &Connection) -> Result { + conn.load_extension_enable().map(|_| LoadExtensionGuard { conn: conn }) } } #[allow(unused_must_use)] -impl<'conn> Drop for SqliteLoadExtensionGuard<'conn> { +impl<'conn> Drop for LoadExtensionGuard<'conn> { fn drop(&mut self) { self.conn.load_extension_disable(); } diff --git a/src/named_params.rs b/src/named_params.rs index 49305e7..d1dcdc9 100644 --- a/src/named_params.rs +++ b/src/named_params.rs @@ -2,11 +2,10 @@ use libc::c_int; use super::ffi; -use {SqliteResult, SqliteError, SqliteConnection, SqliteStatement, SqliteRows, SqliteRow, - str_to_cstring}; +use {Result, Error, Connection, Statement, Rows, Row, str_to_cstring}; use types::ToSql; -impl SqliteConnection { +impl Connection { /// Convenience method to prepare and execute a single SQL statement with named parameter(s). /// /// On success, returns the number of rows that were changed or inserted or deleted (via @@ -15,8 +14,8 @@ impl SqliteConnection { /// ## Example /// /// ```rust,no_run - /// # use rusqlite::{SqliteConnection, SqliteResult}; - /// fn insert(conn: &SqliteConnection) -> SqliteResult { + /// # use rusqlite::{Connection, Result}; + /// fn insert(conn: &Connection) -> Result { /// conn.execute_named("INSERT INTO test (name) VALUES (:name)", &[(":name", &"one")]) /// } /// ``` @@ -25,7 +24,7 @@ impl SqliteConnection { /// /// Will return `Err` if `sql` cannot be converted to a C-compatible string or if the /// underlying SQLite call fails. - pub fn execute_named(&self, sql: &str, params: &[(&str, &ToSql)]) -> SqliteResult { + pub fn execute_named(&self, sql: &str, params: &[(&str, &ToSql)]) -> Result { self.prepare(sql).and_then(|mut stmt| stmt.execute_named(params)) } @@ -42,8 +41,8 @@ impl SqliteConnection { sql: &str, params: &[(&str, &ToSql)], f: F) - -> SqliteResult - where F: FnOnce(SqliteRow) -> T + -> Result + where F: FnOnce(Row) -> T { let mut stmt = try!(self.prepare(sql)); let mut rows = try!(stmt.query_named(params)); @@ -52,14 +51,14 @@ impl SqliteConnection { } } -impl<'conn> SqliteStatement<'conn> { +impl<'conn> Statement<'conn> { /// Return the index of an SQL parameter given its name. /// /// # Failure /// /// Will return Err if `name` is invalid. Will return Ok(None) if the name /// is valid but not a bound parameter of this statement. - pub fn parameter_index(&self, name: &str) -> SqliteResult> { + pub fn parameter_index(&self, name: &str) -> Result> { let c_name = try!(str_to_cstring(name)); let c_index = unsafe { ffi::sqlite3_bind_parameter_index(self.stmt, c_name.as_ptr()) }; Ok(match c_index { @@ -79,8 +78,8 @@ impl<'conn> SqliteStatement<'conn> { /// ## Example /// /// ```rust,no_run - /// # use rusqlite::{SqliteConnection, SqliteResult}; - /// fn insert(conn: &SqliteConnection) -> SqliteResult { + /// # use rusqlite::{Connection, Result}; + /// fn insert(conn: &Connection) -> Result { /// let mut stmt = try!(conn.prepare("INSERT INTO test (name) VALUES (:name)")); /// stmt.execute_named(&[(":name", &"one")]) /// } @@ -90,7 +89,7 @@ impl<'conn> SqliteStatement<'conn> { /// /// 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_named(&mut self, params: &[(&str, &ToSql)]) -> SqliteResult { + pub fn execute_named(&mut self, params: &[(&str, &ToSql)]) -> Result { try!(self.bind_parameters_named(params)); unsafe { self.execute_() @@ -105,8 +104,8 @@ impl<'conn> SqliteStatement<'conn> { /// ## Example /// /// ```rust,no_run - /// # use rusqlite::{SqliteConnection, SqliteResult, SqliteRows}; - /// fn query(conn: &SqliteConnection) -> SqliteResult<()> { + /// # use rusqlite::{Connection, Result, Rows}; + /// fn query(conn: &Connection) -> Result<()> { /// let mut stmt = try!(conn.prepare("SELECT * FROM test where name = :name")); /// let mut rows = try!(stmt.query_named(&[(":name", &"one")])); /// for row in rows { @@ -121,20 +120,20 @@ impl<'conn> SqliteStatement<'conn> { /// Will return `Err` if binding parameters fails. pub fn query_named<'a>(&'a mut self, params: &[(&str, &ToSql)]) - -> SqliteResult> { + -> Result> { self.reset_if_needed(); try!(self.bind_parameters_named(params)); self.needs_reset = true; - Ok(SqliteRows::new(self)) + Ok(Rows::new(self)) } - fn bind_parameters_named(&mut self, params: &[(&str, &ToSql)]) -> SqliteResult<()> { + fn bind_parameters_named(&mut self, params: &[(&str, &ToSql)]) -> Result<()> { for &(name, value) in params { if let Some(i) = try!(self.parameter_index(name)) { try!(self.conn.decode_result(unsafe { value.bind_parameter(self.stmt, i) })); } else { - return Err(SqliteError { + return Err(Error { code: ffi::SQLITE_MISUSE, message: format!("Invalid parameter name: {}", name), }); @@ -146,11 +145,11 @@ impl<'conn> SqliteStatement<'conn> { #[cfg(test)] mod test { - use SqliteConnection; + use Connection; #[test] fn test_execute_named() { - let db = SqliteConnection::open_in_memory().unwrap(); + let db = Connection::open_in_memory().unwrap(); db.execute_batch("CREATE TABLE foo(x INTEGER)").unwrap(); assert_eq!(db.execute_named("INSERT INTO foo(x) VALUES (:x)", &[(":x", &1i32)]).unwrap(), @@ -167,7 +166,7 @@ mod test { #[test] fn test_stmt_execute_named() { - let db = SqliteConnection::open_in_memory().unwrap(); + let db = Connection::open_in_memory().unwrap(); let sql = "CREATE TABLE test (id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL, flag \ INTEGER)"; db.execute_batch(sql).unwrap(); @@ -184,7 +183,7 @@ mod test { #[test] fn test_query_named() { - let db = SqliteConnection::open_in_memory().unwrap(); + let db = Connection::open_in_memory().unwrap(); let sql = "CREATE TABLE test (id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL, flag \ INTEGER)"; db.execute_batch(sql).unwrap(); @@ -195,7 +194,7 @@ mod test { #[test] fn test_unbound_parameters_are_null() { - let db = SqliteConnection::open_in_memory().unwrap(); + let db = Connection::open_in_memory().unwrap(); let sql = "CREATE TABLE test (x TEXT, y TEXT)"; db.execute_batch(sql).unwrap(); @@ -209,7 +208,7 @@ mod test { #[test] fn test_unbound_parameters_are_reused() { - let db = SqliteConnection::open_in_memory().unwrap(); + let db = Connection::open_in_memory().unwrap(); let sql = "CREATE TABLE test (x TEXT, y TEXT)"; db.execute_batch(sql).unwrap(); diff --git a/src/trace.rs b/src/trace.rs index 682662c..eac7fc3 100644 --- a/src/trace.rs +++ b/src/trace.rs @@ -8,7 +8,7 @@ use std::str; use std::time::Duration; use super::ffi; -use {SqliteError, SqliteResult, SqliteConnection}; +use {Error, Result, Connection}; /// Set up the process-wide SQLite error logging callback. /// This function is marked unsafe for two reasons: @@ -21,7 +21,7 @@ use {SqliteError, SqliteResult, SqliteConnection}; /// * It must be threadsafe if SQLite is used in a multithreaded way. /// /// cf [The Error And Warning Log](http://sqlite.org/errlog.html). -pub unsafe fn config_log(callback: Option) -> SqliteResult<()> { +pub unsafe fn config_log(callback: Option) -> Result<()> { 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) }; @@ -43,7 +43,7 @@ pub unsafe fn config_log(callback: Option) -> SqliteResult<()> }; if rc != ffi::SQLITE_OK { - return Err(SqliteError { + return Err(Error { code: rc, message: "sqlite3_config(SQLITE_CONFIG_LOG, ...)".to_string(), }); @@ -60,7 +60,7 @@ pub fn log(err_code: c_int, msg: &str) { } } -impl SqliteConnection { +impl Connection { /// 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. @@ -120,7 +120,7 @@ mod test { use std::sync::Mutex; use std::time::Duration; - use SqliteConnection; + use Connection; #[test] fn test_trace() { @@ -132,7 +132,7 @@ mod test { traced_stmts.push(s.to_owned()); } - let mut db = SqliteConnection::open_in_memory().unwrap(); + let mut db = Connection::open_in_memory().unwrap(); db.trace(Some(tracer)); { let _ = db.query_row("SELECT ?", &[&1i32], |_| {}); @@ -160,7 +160,7 @@ mod test { profiled.push((s.to_owned(), d)); } - let mut db = SqliteConnection::open_in_memory().unwrap(); + let mut db = Connection::open_in_memory().unwrap(); db.profile(Some(profiler)); db.execute_batch("PRAGMA application_id = 1").unwrap(); db.profile(None); diff --git a/src/transaction.rs b/src/transaction.rs index 1981f24..3adbdb2 100644 --- a/src/transaction.rs +++ b/src/transaction.rs @@ -1,17 +1,21 @@ -use {SqliteResult, SqliteConnection}; +use {Result, Connection}; -pub use SqliteTransactionBehavior::{SqliteTransactionDeferred, SqliteTransactionImmediate, - SqliteTransactionExclusive}; +/// Old name for `TransactionBehavior`. `SqliteTransactionBehavior` is deprecated. +pub type SqliteTransactionBehavior = TransactionBehavior; /// Options for transaction behavior. See [BEGIN /// TRANSACTION](http://www.sqlite.org/lang_transaction.html) for details. #[derive(Copy,Clone)] -pub enum SqliteTransactionBehavior { - SqliteTransactionDeferred, - SqliteTransactionImmediate, - SqliteTransactionExclusive, +pub enum TransactionBehavior { + Deferred, + Immediate, + Exclusive, } +/// Old name for `Transaction`. `SqliteTransaction` is deprecated. +pub type SqliteTransaction<'conn> = Transaction<'conn>; + +/// /// Represents a transaction on a database connection. /// /// ## Note @@ -22,10 +26,10 @@ pub enum SqliteTransactionBehavior { /// ## Example /// /// ```rust,no_run -/// # use rusqlite::{SqliteConnection, SqliteResult}; -/// # fn do_queries_part_1(conn: &SqliteConnection) -> SqliteResult<()> { Ok(()) } -/// # fn do_queries_part_2(conn: &SqliteConnection) -> SqliteResult<()> { Ok(()) } -/// fn perform_queries(conn: &SqliteConnection) -> SqliteResult<()> { +/// # use rusqlite::{Connection, Result}; +/// # fn do_queries_part_1(conn: &Connection) -> Result<()> { Ok(()) } +/// # fn do_queries_part_2(conn: &Connection) -> Result<()> { Ok(()) } +/// fn perform_queries(conn: &Connection) -> Result<()> { /// let tx = try!(conn.transaction()); /// /// try!(do_queries_part_1(conn)); // tx causes rollback if this fails @@ -34,25 +38,25 @@ pub enum SqliteTransactionBehavior { /// tx.commit() /// } /// ``` -pub struct SqliteTransaction<'conn> { - conn: &'conn SqliteConnection, +pub struct Transaction<'conn> { + conn: &'conn Connection, depth: u32, commit: bool, finished: bool, } -impl<'conn> SqliteTransaction<'conn> { +impl<'conn> Transaction<'conn> { /// Begin a new transaction. Cannot be nested; see `savepoint` for nested transactions. - pub fn new(conn: &SqliteConnection, - behavior: SqliteTransactionBehavior) - -> SqliteResult { + pub fn new(conn: &Connection, + behavior: TransactionBehavior) + -> Result { let query = match behavior { - SqliteTransactionDeferred => "BEGIN DEFERRED", - SqliteTransactionImmediate => "BEGIN IMMEDIATE", - SqliteTransactionExclusive => "BEGIN EXCLUSIVE", + TransactionBehavior::Deferred => "BEGIN DEFERRED", + TransactionBehavior::Immediate => "BEGIN IMMEDIATE", + TransactionBehavior::Exclusive => "BEGIN EXCLUSIVE", }; conn.execute_batch(query).map(|_| { - SqliteTransaction { + Transaction { conn: conn, depth: 0, commit: false, @@ -71,9 +75,9 @@ impl<'conn> SqliteTransaction<'conn> { /// ## Example /// /// ```rust,no_run - /// # use rusqlite::{SqliteConnection, SqliteResult}; - /// # fn perform_queries_part_1_succeeds(conn: &SqliteConnection) -> bool { true } - /// fn perform_queries(conn: &SqliteConnection) -> SqliteResult<()> { + /// # use rusqlite::{Connection, Result}; + /// # fn perform_queries_part_1_succeeds(conn: &Connection) -> bool { true } + /// fn perform_queries(conn: &Connection) -> Result<()> { /// let tx = try!(conn.transaction()); /// /// { @@ -87,9 +91,9 @@ impl<'conn> SqliteTransaction<'conn> { /// tx.commit() /// } /// ``` - pub fn savepoint<'a>(&'a self) -> SqliteResult> { + pub fn savepoint<'a>(&'a self) -> Result> { self.conn.execute_batch("SAVEPOINT sp").map(|_| { - SqliteTransaction { + Transaction { conn: self.conn, depth: self.depth + 1, commit: false, @@ -119,11 +123,11 @@ impl<'conn> SqliteTransaction<'conn> { } /// A convenience method which consumes and commits a transaction. - pub fn commit(mut self) -> SqliteResult<()> { + pub fn commit(mut self) -> Result<()> { self.commit_() } - fn commit_(&mut self) -> SqliteResult<()> { + fn commit_(&mut self) -> Result<()> { self.finished = true; self.conn.execute_batch(if self.depth == 0 { "COMMIT" @@ -133,11 +137,11 @@ impl<'conn> SqliteTransaction<'conn> { } /// A convenience method which consumes and rolls back a transaction. - pub fn rollback(mut self) -> SqliteResult<()> { + pub fn rollback(mut self) -> Result<()> { self.rollback_() } - fn rollback_(&mut self) -> SqliteResult<()> { + fn rollback_(&mut self) -> Result<()> { self.finished = true; self.conn.execute_batch(if self.depth == 0 { "ROLLBACK" @@ -151,11 +155,11 @@ impl<'conn> SqliteTransaction<'conn> { /// /// Functionally equivalent to the `Drop` implementation, but allows callers to see any /// errors that occur. - pub fn finish(mut self) -> SqliteResult<()> { + pub fn finish(mut self) -> Result<()> { self.finish_() } - fn finish_(&mut self) -> SqliteResult<()> { + fn finish_(&mut self) -> Result<()> { match (self.finished, self.commit) { (true, _) => Ok(()), (false, true) => self.commit_(), @@ -165,7 +169,7 @@ impl<'conn> SqliteTransaction<'conn> { } #[allow(unused_must_use)] -impl<'conn> Drop for SqliteTransaction<'conn> { +impl<'conn> Drop for Transaction<'conn> { fn drop(&mut self) { self.finish_(); } @@ -173,10 +177,10 @@ impl<'conn> Drop for SqliteTransaction<'conn> { #[cfg(test)] mod test { - use SqliteConnection; + use Connection; - fn checked_memory_handle() -> SqliteConnection { - let db = SqliteConnection::open_in_memory().unwrap(); + fn checked_memory_handle() -> Connection { + let db = Connection::open_in_memory().unwrap(); db.execute_batch("CREATE TABLE foo (x INTEGER)").unwrap(); db } diff --git a/src/types.rs b/src/types.rs index ddc0234..f0852ab 100644 --- a/src/types.rs +++ b/src/types.rs @@ -26,7 +26,7 @@ //! extern crate libc; //! //! use rusqlite::types::{FromSql, ToSql, sqlite3_stmt}; -//! use rusqlite::{SqliteResult}; +//! use rusqlite::{Result}; //! use libc::c_int; //! use time; //! @@ -34,7 +34,7 @@ //! //! impl FromSql for TimespecSql { //! unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -//! -> SqliteResult { +//! -> Result { //! let as_f64_result = FromSql::column_result(stmt, col); //! as_f64_result.map(|as_f64: f64| { //! TimespecSql(time::Timespec{ sec: as_f64.trunc() as i64, @@ -59,7 +59,7 @@ use std::ffi::CStr; use std::mem; use std::str; use super::ffi; -use super::{SqliteResult, SqliteError, str_to_cstring}; +use super::{Result, Error, str_to_cstring}; pub use ffi::sqlite3_stmt; pub use ffi::sqlite3_column_type; @@ -75,11 +75,11 @@ pub trait ToSql { /// A trait for types that can be created from a SQLite value. pub trait FromSql: Sized { - unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> SqliteResult; + unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result; /// FromSql types can implement this method and use sqlite3_column_type to check that /// the type reported by SQLite matches a type suitable for Self. This method is used - /// by `SqliteRow::get_checked` to confirm that the column contains a valid type before + /// by `Row::get_checked` to confirm that the column contains a valid type before /// attempting to retrieve the value. unsafe fn column_has_valid_sqlite_type(_: *mut sqlite3_stmt, _: c_int) -> bool { true @@ -176,12 +176,12 @@ impl ToSql for Option { /// ```rust,no_run /// # extern crate libc; /// # extern crate rusqlite; -/// # use rusqlite::{SqliteConnection, SqliteResult}; +/// # use rusqlite::{Connection, Result}; /// # use rusqlite::types::{Null}; /// # use libc::{c_int}; /// fn main() { /// } -/// fn insert_null(conn: &SqliteConnection) -> SqliteResult { +/// fn insert_null(conn: &Connection) -> Result { /// conn.execute("INSERT INTO people (name) VALUES (?)", &[&Null]) /// } /// ``` @@ -197,7 +197,7 @@ impl ToSql for Null { macro_rules! raw_from_impl( ($t:ty, $f:ident, $c:expr) => ( impl FromSql for $t { - unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> SqliteResult<$t> { + unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<$t> { Ok(ffi::$f(stmt, col)) } @@ -213,7 +213,7 @@ raw_from_impl!(i64, sqlite3_column_int64, ffi::SQLITE_INTEGER); raw_from_impl!(c_double, sqlite3_column_double, ffi::SQLITE_FLOAT); impl FromSql for bool { - unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> SqliteResult { + unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result { match ffi::sqlite3_column_int(stmt, col) { 0 => Ok(false), _ => Ok(true), @@ -226,7 +226,7 @@ impl FromSql for bool { } impl FromSql for String { - unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> SqliteResult { + unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result { let c_text = ffi::sqlite3_column_text(stmt, col); if c_text.is_null() { Ok("".to_string()) @@ -235,7 +235,7 @@ impl FromSql for String { let utf8_str = str::from_utf8(c_slice); utf8_str.map(|s| s.to_string()) .map_err(|e| { - SqliteError { + Error { code: 0, message: e.to_string(), } @@ -249,7 +249,7 @@ impl FromSql for String { } impl FromSql for Vec { - unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> SqliteResult> { + unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result> { use std::slice::from_raw_parts; let c_blob = ffi::sqlite3_column_blob(stmt, col); let len = ffi::sqlite3_column_bytes(stmt, col); @@ -269,13 +269,13 @@ impl FromSql for Vec { } impl FromSql for time::Timespec { - unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> SqliteResult { + unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result { let col_str = FromSql::column_result(stmt, col); col_str.and_then(|txt: String| { time::strptime(&txt, SQLITE_DATETIME_FMT) .map(|tm| tm.to_timespec()) .map_err(|parse_error| { - SqliteError { + Error { code: ffi::SQLITE_MISMATCH, message: format!("{}", parse_error), } @@ -289,7 +289,7 @@ impl FromSql for time::Timespec { } impl FromSql for Option { - unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> SqliteResult> { + unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result> { if sqlite3_column_type(stmt, col) == ffi::SQLITE_NULL { Ok(None) } else { @@ -305,13 +305,13 @@ impl FromSql for Option { #[cfg(test)] mod test { - use SqliteConnection; + use Connection; use ffi; use super::time; use libc::{c_int, c_double}; - fn checked_memory_handle() -> SqliteConnection { - let db = SqliteConnection::open_in_memory().unwrap(); + fn checked_memory_handle() -> Connection { + let db = Connection::open_in_memory().unwrap(); db.execute_batch("CREATE TABLE foo (b BLOB, t TEXT, i INTEGER, f FLOAT, n)").unwrap(); db }