Rust 2018

This commit is contained in:
gwenn 2018-10-30 20:11:35 +01:00
parent ebc3609a09
commit f04047db01
30 changed files with 236 additions and 234 deletions

View File

@ -2,6 +2,7 @@
name = "rusqlite" name = "rusqlite"
version = "0.15.0" version = "0.15.0"
authors = ["John Gallagher <jgallagher@bignerdranch.com>"] authors = ["John Gallagher <jgallagher@bignerdranch.com>"]
edition = "2018"
description = "Ergonomic wrapper for SQLite" description = "Ergonomic wrapper for SQLite"
repository = "https://github.com/jgallagher/rusqlite" repository = "https://github.com/jgallagher/rusqlite"
documentation = "http://docs.rs/rusqlite/" documentation = "http://docs.rs/rusqlite/"

View File

@ -2,6 +2,7 @@
name = "libsqlite3-sys" name = "libsqlite3-sys"
version = "0.10.0" version = "0.10.0"
authors = ["John Gallagher <jgallagher@bignerdranch.com>"] authors = ["John Gallagher <jgallagher@bignerdranch.com>"]
edition = "2018"
repository = "https://github.com/jgallagher/rusqlite" repository = "https://github.com/jgallagher/rusqlite"
description = "Native bindings to the libsqlite3 library" description = "Native bindings to the libsqlite3 library"
license = "MIT" license = "MIT"

View File

@ -23,8 +23,8 @@
//! dst: P, //! dst: P,
//! progress: fn(backup::Progress), //! progress: fn(backup::Progress),
//! ) -> Result<()> { //! ) -> Result<()> {
//! let mut dst = try!(Connection::open(dst)); //! let mut dst = Connection::open(dst)?;
//! let backup = try!(backup::Backup::new(src, &mut dst)); //! let backup = backup::Backup::new(src, &mut dst)?;
//! backup.run_to_completion(5, time::Duration::from_millis(250), Some(progress)) //! backup.run_to_completion(5, time::Duration::from_millis(250), Some(progress))
//! } //! }
//! ``` //! ```
@ -37,10 +37,10 @@ use std::os::raw::c_int;
use std::thread; use std::thread;
use std::time::Duration; use std::time::Duration;
use ffi; use crate::ffi;
use error::{error_from_handle, error_from_sqlite_code}; use crate::error::{error_from_handle, error_from_sqlite_code};
use {Connection, DatabaseName, Result}; use crate::{Connection, DatabaseName, Result};
impl Connection { impl Connection {
/// Back up the `name` database to the given destination path. /// Back up the `name` database to the given destination path.
@ -62,17 +62,17 @@ impl Connection {
progress: Option<fn(Progress)>, progress: Option<fn(Progress)>,
) -> Result<()> { ) -> Result<()> {
use self::StepResult::{Busy, Done, Locked, More}; use self::StepResult::{Busy, Done, Locked, More};
let mut dst = try!(Connection::open(dst_path)); let mut dst = Connection::open(dst_path)?;
let backup = try!(Backup::new_with_names( let backup = Backup::new_with_names(
self, self,
name, name,
&mut dst, &mut dst,
DatabaseName::Main DatabaseName::Main
)); )?;
let mut r = More; let mut r = More;
while r == More { while r == More {
r = try!(backup.step(100)); r = backup.step(100)?;
if let Some(f) = progress { if let Some(f) = progress {
f(backup.progress()); f(backup.progress());
} }
@ -105,13 +105,13 @@ impl Connection {
progress: Option<F>, progress: Option<F>,
) -> Result<()> { ) -> Result<()> {
use self::StepResult::{Busy, Done, Locked, More}; use self::StepResult::{Busy, Done, Locked, More};
let src = try!(Connection::open(src_path)); let src = Connection::open(src_path)?;
let restore = try!(Backup::new_with_names(&src, DatabaseName::Main, self, name)); let restore = Backup::new_with_names(&src, DatabaseName::Main, self, name)?;
let mut r = More; let mut r = More;
let mut busy_count = 0i32; let mut busy_count = 0i32;
'restore_loop: while r == More || r == Busy { 'restore_loop: while r == More || r == Busy {
r = try!(restore.step(100)); r = restore.step(100)?;
if let Some(ref f) = progress { if let Some(ref f) = progress {
f(restore.progress()); f(restore.progress());
} }
@ -201,8 +201,8 @@ impl<'a, 'b> Backup<'a, 'b> {
to: &'b mut Connection, to: &'b mut Connection,
to_name: DatabaseName, to_name: DatabaseName,
) -> Result<Backup<'a, 'b>> { ) -> Result<Backup<'a, 'b>> {
let to_name = try!(to_name.to_cstring()); let to_name = to_name.to_cstring()?;
let from_name = try!(from_name.to_cstring()); let from_name = from_name.to_cstring()?;
let to_db = to.db.borrow_mut().db; let to_db = to.db.borrow_mut().db;
@ -287,7 +287,7 @@ impl<'a, 'b> Backup<'a, 'b> {
assert!(pages_per_step > 0, "pages_per_step must be positive"); assert!(pages_per_step > 0, "pages_per_step must be positive");
loop { loop {
let r = try!(self.step(pages_per_step)); let r = self.step(pages_per_step)?;
if let Some(progress) = progress { if let Some(progress) = progress {
progress(self.progress()) progress(self.progress())
} }
@ -309,7 +309,7 @@ impl<'a, 'b> Drop for Backup<'a, 'b> {
mod test { mod test {
use super::Backup; use super::Backup;
use std::time::Duration; use std::time::Duration;
use {Connection, DatabaseName, NO_PARAMS}; use crate::{Connection, DatabaseName, NO_PARAMS};
#[test] #[test]
fn test_backup() { fn test_backup() {

View File

@ -64,7 +64,7 @@ use std::ptr;
use super::ffi; use super::ffi;
use super::types::{ToSql, ToSqlOutput}; use super::types::{ToSql, ToSqlOutput};
use {Connection, DatabaseName, Result}; use crate::{Connection, DatabaseName, Result};
/// Handle to an open BLOB. /// Handle to an open BLOB.
pub struct Blob<'conn> { pub struct Blob<'conn> {
@ -92,9 +92,9 @@ impl Connection {
) -> Result<Blob<'a>> { ) -> Result<Blob<'a>> {
let mut c = self.db.borrow_mut(); let mut c = self.db.borrow_mut();
let mut blob = ptr::null_mut(); let mut blob = ptr::null_mut();
let db = try!(db.to_cstring()); let db = db.to_cstring()?;
let table = try!(super::str_to_cstring(table)); let table = super::str_to_cstring(table)?;
let column = try!(super::str_to_cstring(column)); let column = super::str_to_cstring(column)?;
let rc = unsafe { let rc = unsafe {
ffi::sqlite3_blob_open( ffi::sqlite3_blob_open(
c.db(), c.db(),
@ -263,15 +263,15 @@ impl ToSql for ZeroBlob {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use std::io::{BufRead, BufReader, BufWriter, Read, Seek, SeekFrom, Write}; use std::io::{BufRead, BufReader, BufWriter, Read, Seek, SeekFrom, Write};
use {Connection, DatabaseName, Result}; use crate::{Connection, DatabaseName, Result};
fn db_with_test_blob() -> Result<(Connection, i64)> { fn db_with_test_blob() -> Result<(Connection, i64)> {
let db = try!(Connection::open_in_memory()); let db = Connection::open_in_memory()?;
let sql = "BEGIN; let sql = "BEGIN;
CREATE TABLE test (content BLOB); CREATE TABLE test (content BLOB);
INSERT INTO test VALUES (ZEROBLOB(10)); INSERT INTO test VALUES (ZEROBLOB(10));
END;"; END;";
try!(db.execute_batch(sql)); db.execute_batch(sql)?;
let rowid = db.last_insert_rowid(); let rowid = db.last_insert_rowid();
Ok((db, rowid)) Ok((db, rowid))
} }

View File

@ -4,8 +4,8 @@ use std::os::raw::{c_int, c_void};
use std::ptr; use std::ptr;
use std::time::Duration; use std::time::Duration;
use ffi; use crate::ffi;
use {Connection, InnerConnection, Result}; use crate::{Connection, InnerConnection, Result};
impl Connection { impl Connection {
/// Set a busy handler that sleeps for a specified amount of time when a /// Set a busy handler that sleeps for a specified amount of time when a
@ -81,7 +81,7 @@ mod test {
use std::thread; use std::thread;
use std::time::Duration; use std::time::Duration;
use {Connection, Error, ErrorCode, TransactionBehavior, NO_PARAMS}; use crate::{Connection, Error, ErrorCode, TransactionBehavior, NO_PARAMS};
#[test] #[test]
fn test_default_busy() { fn test_default_busy() {

View File

@ -1,10 +1,10 @@
//! Prepared statements cache for faster execution. //! Prepared statements cache for faster execution.
use lru_cache::LruCache; use lru_cache::LruCache;
use raw_statement::RawStatement; use crate::raw_statement::RawStatement;
use std::cell::RefCell; use std::cell::RefCell;
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};
use {Connection, Result, Statement}; use crate::{Connection, Result, Statement};
impl Connection { impl Connection {
/// Prepare a SQL statement for execution, returning a previously prepared /// Prepare a SQL statement for execution, returning a previously prepared
@ -16,14 +16,14 @@ impl Connection {
/// # use rusqlite::{Connection, Result}; /// # use rusqlite::{Connection, Result};
/// fn insert_new_people(conn: &Connection) -> Result<()> { /// fn insert_new_people(conn: &Connection) -> Result<()> {
/// { /// {
/// let mut stmt = try!(conn.prepare_cached("INSERT INTO People (name) VALUES (?)")); /// let mut stmt = conn.prepare_cached("INSERT INTO People (name) VALUES (?)")?;
/// try!(stmt.execute(&["Joe Smith"])); /// stmt.execute(&["Joe Smith"])?;
/// } /// }
/// { /// {
/// // This will return the same underlying SQLite statement handle without /// // This will return the same underlying SQLite statement handle without
/// // having to prepare it again. /// // having to prepare it again.
/// let mut stmt = try!(conn.prepare_cached("INSERT INTO People (name) VALUES (?)")); /// let mut stmt = conn.prepare_cached("INSERT INTO People (name) VALUES (?)")?;
/// try!(stmt.execute(&["Bob Jones"])); /// stmt.execute(&["Bob Jones"])?;
/// } /// }
/// Ok(()) /// Ok(())
/// } /// }
@ -152,7 +152,7 @@ impl StatementCache {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use super::StatementCache; use super::StatementCache;
use {Connection, NO_PARAMS}; use crate::{Connection, NO_PARAMS};
impl StatementCache { impl StatementCache {
fn clear(&self) { fn clear(&self) {

View File

@ -5,14 +5,14 @@ use std::os::raw::{c_char, c_int, c_void};
#[cfg(feature = "array")] #[cfg(feature = "array")]
use std::rc::Rc; use std::rc::Rc;
use ffi; use crate::ffi;
use ffi::sqlite3_context; use crate::ffi::sqlite3_context;
use ffi::sqlite3_value; use crate::ffi::sqlite3_value;
use str_to_cstring; use crate::str_to_cstring;
use types::{ToSqlOutput, ValueRef}; use crate::types::{ToSqlOutput, ValueRef};
#[cfg(feature = "array")] #[cfg(feature = "array")]
use vtab::array::{free_array, ARRAY_TYPE}; use crate::vtab::array::{free_array, ARRAY_TYPE};
impl<'a> ValueRef<'a> { impl<'a> ValueRef<'a> {
pub(crate) unsafe fn from_value(value: *mut sqlite3_value) -> ValueRef<'a> { pub(crate) unsafe fn from_value(value: *mut sqlite3_value) -> ValueRef<'a> {

View File

@ -3,8 +3,8 @@ use std::fmt;
use std::os::raw::c_int; use std::os::raw::c_int;
use std::path::PathBuf; use std::path::PathBuf;
use std::str; use std::str;
use types::Type; use crate::types::Type;
use {errmsg_to_string, ffi}; use crate::{errmsg_to_string, ffi};
/// Old name for `Error`. `SqliteError` is deprecated. /// Old name for `Error`. `SqliteError` is deprecated.
#[deprecated(since = "0.6.0", note = "Use Error instead")] #[deprecated(since = "0.6.0", note = "Use Error instead")]

View File

@ -20,7 +20,7 @@
//! fn add_regexp_function(db: &Connection) -> Result<()> { //! fn add_regexp_function(db: &Connection) -> Result<()> {
//! let mut cached_regexes = HashMap::new(); //! let mut cached_regexes = HashMap::new();
//! db.create_scalar_function("regexp", 2, true, move |ctx| { //! db.create_scalar_function("regexp", 2, true, move |ctx| {
//! let regex_s = try!(ctx.get::<String>(0)); //! let regex_s = ctx.get::<String>(0)?;
//! let entry = cached_regexes.entry(regex_s.clone()); //! let entry = cached_regexes.entry(regex_s.clone());
//! let regex = { //! let regex = {
//! use std::collections::hash_map::Entry::{Occupied, Vacant}; //! use std::collections::hash_map::Entry::{Occupied, Vacant};
@ -33,7 +33,7 @@
//! } //! }
//! }; //! };
//! //!
//! let text = try!(ctx.get::<String>(1)); //! let text = ctx.get::<String>(1)?;
//! Ok(regex.is_match(&text)) //! Ok(regex.is_match(&text))
//! }) //! })
//! } //! }
@ -58,14 +58,14 @@ use std::os::raw::{c_int, c_void};
use std::ptr; use std::ptr;
use std::slice; use std::slice;
use ffi; use crate::ffi;
use ffi::sqlite3_context; use crate::ffi::sqlite3_context;
use ffi::sqlite3_value; use crate::ffi::sqlite3_value;
use context::set_result; use crate::context::set_result;
use types::{FromSql, FromSqlError, ToSql, ValueRef}; use crate::types::{FromSql, FromSqlError, ToSql, ValueRef};
use {str_to_cstring, Connection, Error, InnerConnection, Result}; use crate::{str_to_cstring, Connection, Error, InnerConnection, Result};
unsafe fn report_error(ctx: *mut sqlite3_context, err: &Error) { unsafe fn report_error(ctx: *mut sqlite3_context, err: &Error) {
// Extended constraint error codes were added in SQLite 3.7.16. We don't have // Extended constraint error codes were added in SQLite 3.7.16. We don't have
@ -198,14 +198,14 @@ where
/// "step" function called once for each row in an aggregate group. May be /// "step" function called once for each row in an aggregate group. May be
/// called 0 times if there are no rows. /// called 0 times if there are no rows.
fn step(&self, &mut Context, &mut A) -> Result<()>; fn step(&self, _: &mut Context, _: &mut A) -> Result<()>;
/// Computes and returns the final result. Will be called exactly once for /// Computes and returns the final result. Will be called exactly once for
/// each invocation of the function. If `step()` was called at least /// each invocation of the function. If `step()` was called at least
/// once, will be given `Some(A)` (the same `A` as was created by /// once, will be given `Some(A)` (the same `A` as was created by
/// `init` and given to `step`); if `step()` was not called (because /// `init` and given to `step`); if `step()` was not called (because
/// the function is running against 0 rows), will be given `None`. /// the function is running against 0 rows), will be given `None`.
fn finalize(&self, Option<A>) -> Result<T>; fn finalize(&self, _: Option<A>) -> Result<T>;
} }
impl Connection { impl Connection {
@ -224,12 +224,12 @@ impl Connection {
/// ```rust /// ```rust
/// # use rusqlite::{Connection, Result, NO_PARAMS}; /// # use rusqlite::{Connection, Result, NO_PARAMS};
/// fn scalar_function_example(db: Connection) -> Result<()> { /// fn scalar_function_example(db: Connection) -> Result<()> {
/// try!(db.create_scalar_function("halve", 1, true, |ctx| { /// db.create_scalar_function("halve", 1, true, |ctx| {
/// let value = try!(ctx.get::<f64>(0)); /// let value = ctx.get::<f64>(0)?;
/// Ok(value / 2f64) /// Ok(value / 2f64)
/// })); /// })?;
/// ///
/// let six_halved: f64 = try!(db.query_row("SELECT halve(6)", NO_PARAMS, |r| r.get(0))); /// let six_halved: f64 = db.query_row("SELECT halve(6)", NO_PARAMS, |r| r.get(0))?;
/// assert_eq!(six_halved, 3f64); /// assert_eq!(six_halved, 3f64);
/// Ok(()) /// Ok(())
/// } /// }
@ -326,7 +326,7 @@ impl InnerConnection {
} }
let boxed_f: *mut F = Box::into_raw(Box::new(x_func)); let boxed_f: *mut F = Box::into_raw(Box::new(x_func));
let c_name = try!(str_to_cstring(fn_name)); let c_name = str_to_cstring(fn_name)?;
let mut flags = ffi::SQLITE_UTF8; let mut flags = ffi::SQLITE_UTF8;
if deterministic { if deterministic {
flags |= ffi::SQLITE_DETERMINISTIC; flags |= ffi::SQLITE_DETERMINISTIC;
@ -441,7 +441,7 @@ impl InnerConnection {
} }
let boxed_aggr: *mut D = Box::into_raw(Box::new(aggr)); let boxed_aggr: *mut D = Box::into_raw(Box::new(aggr));
let c_name = try!(str_to_cstring(fn_name)); let c_name = str_to_cstring(fn_name)?;
let mut flags = ffi::SQLITE_UTF8; let mut flags = ffi::SQLITE_UTF8;
if deterministic { if deterministic {
flags |= ffi::SQLITE_DETERMINISTIC; flags |= ffi::SQLITE_DETERMINISTIC;
@ -463,7 +463,7 @@ impl InnerConnection {
} }
fn remove_function(&mut self, fn_name: &str, n_arg: c_int) -> Result<()> { fn remove_function(&mut self, fn_name: &str, n_arg: c_int) -> Result<()> {
let c_name = try!(str_to_cstring(fn_name)); let c_name = str_to_cstring(fn_name)?;
let r = unsafe { let r = unsafe {
ffi::sqlite3_create_function_v2( ffi::sqlite3_create_function_v2(
self.db(), self.db(),
@ -490,12 +490,12 @@ mod test {
use std::f64::EPSILON; use std::f64::EPSILON;
use std::os::raw::c_double; use std::os::raw::c_double;
use functions::{Aggregate, Context}; use crate::functions::{Aggregate, Context};
use {Connection, Error, Result, NO_PARAMS}; use crate::{Connection, Error, Result, NO_PARAMS};
fn half(ctx: &Context) -> Result<c_double> { fn half(ctx: &Context) -> Result<c_double> {
assert!(ctx.len() == 1, "called with unexpected number of arguments"); assert!(ctx.len() == 1, "called with unexpected number of arguments");
let value = try!(ctx.get::<c_double>(0)); let value = ctx.get::<c_double>(0)?;
Ok(value / 2f64) Ok(value / 2f64)
} }
@ -529,7 +529,7 @@ mod test {
let saved_re: Option<&Regex> = unsafe { ctx.get_aux(0) }; let saved_re: Option<&Regex> = unsafe { ctx.get_aux(0) };
let new_re = match saved_re { let new_re = match saved_re {
None => { None => {
let s = try!(ctx.get::<String>(0)); let s = ctx.get::<String>(0)?;
match Regex::new(&s) { match Regex::new(&s) {
Ok(r) => Some(r), Ok(r) => Some(r),
Err(err) => return Err(Error::UserFunctionError(Box::new(err))), Err(err) => return Err(Error::UserFunctionError(Box::new(err))),
@ -607,7 +607,7 @@ mod test {
db.create_scalar_function("regexp", 2, true, move |ctx| { db.create_scalar_function("regexp", 2, true, move |ctx| {
assert!(ctx.len() == 2, "called with unexpected number of arguments"); assert!(ctx.len() == 2, "called with unexpected number of arguments");
let regex_s = try!(ctx.get::<String>(0)); let regex_s = ctx.get::<String>(0)?;
let entry = cached_regexes.entry(regex_s.clone()); let entry = cached_regexes.entry(regex_s.clone());
let regex = { let regex = {
use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::collections::hash_map::Entry::{Occupied, Vacant};
@ -620,7 +620,7 @@ mod test {
} }
}; };
let text = try!(ctx.get::<String>(1)); let text = ctx.get::<String>(1)?;
Ok(regex.is_match(&text)) Ok(regex.is_match(&text))
}) })
.unwrap(); .unwrap();
@ -648,7 +648,7 @@ mod test {
let mut ret = String::new(); let mut ret = String::new();
for idx in 0..ctx.len() { for idx in 0..ctx.len() {
let s = try!(ctx.get::<String>(idx)); let s = ctx.get::<String>(idx)?;
ret.push_str(&s); ret.push_str(&s);
} }
@ -675,7 +675,7 @@ mod test {
} }
fn step(&self, ctx: &mut Context, sum: &mut i64) -> Result<()> { fn step(&self, ctx: &mut Context, sum: &mut i64) -> Result<()> {
*sum += try!(ctx.get::<i64>(0)); *sum += ctx.get::<i64>(0)?;
Ok(()) Ok(())
} }

View File

@ -4,9 +4,9 @@
use std::os::raw::{c_char, c_int, c_void}; use std::os::raw::{c_char, c_int, c_void};
use std::ptr; use std::ptr;
use ffi; use crate::ffi;
use {Connection, InnerConnection}; use crate::{Connection, InnerConnection};
/// Authorizer Action Codes /// Authorizer Action Codes
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
@ -290,7 +290,7 @@ fn free_boxed_hook<F>(p: *mut c_void) {
mod test { mod test {
use super::Action; use super::Action;
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use Connection; use crate::Connection;
#[test] #[test]
fn test_commit_hook() { fn test_commit_hook() {

View File

@ -88,32 +88,32 @@ use std::str;
use std::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT}; use std::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT};
use std::sync::{Arc, Mutex, Once, ONCE_INIT}; use std::sync::{Arc, Mutex, Once, ONCE_INIT};
use cache::StatementCache; use crate::cache::StatementCache;
use error::{error_from_handle, error_from_sqlite_code}; use crate::error::{error_from_handle, error_from_sqlite_code};
use raw_statement::RawStatement; use crate::raw_statement::RawStatement;
use types::{ToSql, ValueRef}; use crate::types::{ToSql, ValueRef};
pub use statement::Statement; pub use crate::statement::Statement;
pub use row::{AndThenRows, MappedRows, Row, RowIndex, Rows}; pub use crate::row::{AndThenRows, MappedRows, Row, RowIndex, Rows};
pub use transaction::{DropBehavior, Savepoint, Transaction, TransactionBehavior}; pub use crate::transaction::{DropBehavior, Savepoint, Transaction, TransactionBehavior};
#[allow(deprecated)] #[allow(deprecated)]
pub use transaction::{SqliteTransaction, SqliteTransactionBehavior}; pub use crate::transaction::{SqliteTransaction, SqliteTransactionBehavior};
pub use error::Error; pub use crate::error::Error;
#[allow(deprecated)] #[allow(deprecated)]
pub use error::SqliteError; pub use crate::error::SqliteError;
pub use ffi::ErrorCode; pub use crate::ffi::ErrorCode;
pub use cache::CachedStatement; pub use crate::cache::CachedStatement;
pub use version::*; pub use crate::version::*;
#[cfg(feature = "hooks")] #[cfg(feature = "hooks")]
pub use hooks::*; pub use crate::hooks::*;
#[cfg(feature = "load_extension")] #[cfg(feature = "load_extension")]
#[allow(deprecated)] #[allow(deprecated)]
pub use load_extension_guard::{LoadExtensionGuard, SqliteLoadExtensionGuard}; pub use crate::load_extension_guard::{LoadExtensionGuard, SqliteLoadExtensionGuard};
#[cfg(feature = "backup")] #[cfg(feature = "backup")]
pub mod backup; pub mod backup;
@ -162,11 +162,11 @@ unsafe fn errmsg_to_string(errmsg: *const c_char) -> String {
} }
fn str_to_cstring(s: &str) -> Result<CString> { fn str_to_cstring(s: &str) -> Result<CString> {
Ok(try!(CString::new(s))) Ok(CString::new(s)?)
} }
fn path_to_cstring(p: &Path) -> Result<CString> { fn path_to_cstring(p: &Path) -> Result<CString> {
let s = try!(p.to_str().ok_or_else(|| Error::InvalidPath(p.to_owned()))); let s = p.to_str().ok_or_else(|| Error::InvalidPath(p.to_owned()))?;
str_to_cstring(s) str_to_cstring(s)
} }
@ -253,7 +253,7 @@ impl Connection {
/// Will return `Err` if `path` cannot be converted to a C-compatible /// Will return `Err` if `path` cannot be converted to a C-compatible
/// string or if the underlying SQLite open call fails. /// string or if the underlying SQLite open call fails.
pub fn open_with_flags<P: AsRef<Path>>(path: P, flags: OpenFlags) -> Result<Connection> { pub fn open_with_flags<P: AsRef<Path>>(path: P, flags: OpenFlags) -> Result<Connection> {
let c_path = try!(path_to_cstring(path.as_ref())); let c_path = path_to_cstring(path.as_ref())?;
InnerConnection::open_with_flags(&c_path, flags).map(|db| Connection { InnerConnection::open_with_flags(&c_path, flags).map(|db| Connection {
db: RefCell::new(db), db: RefCell::new(db),
cache: StatementCache::with_capacity(STATEMENT_CACHE_DEFAULT_CAPACITY), cache: StatementCache::with_capacity(STATEMENT_CACHE_DEFAULT_CAPACITY),
@ -270,7 +270,7 @@ impl Connection {
/// ///
/// Will return `Err` if the underlying SQLite open call fails. /// Will return `Err` if the underlying SQLite open call fails.
pub fn open_in_memory_with_flags(flags: OpenFlags) -> Result<Connection> { pub fn open_in_memory_with_flags(flags: OpenFlags) -> Result<Connection> {
let c_memory = try!(str_to_cstring(":memory:")); let c_memory = str_to_cstring(":memory:")?;
InnerConnection::open_with_flags(&c_memory, flags).map(|db| Connection { InnerConnection::open_with_flags(&c_memory, flags).map(|db| Connection {
db: RefCell::new(db), db: RefCell::new(db),
cache: StatementCache::with_capacity(STATEMENT_CACHE_DEFAULT_CAPACITY), cache: StatementCache::with_capacity(STATEMENT_CACHE_DEFAULT_CAPACITY),
@ -398,7 +398,7 @@ impl Connection {
P::Item: ToSql, P::Item: ToSql,
F: FnOnce(&Row) -> T, F: FnOnce(&Row) -> T,
{ {
let mut stmt = try!(self.prepare(sql)); let mut stmt = self.prepare(sql)?;
stmt.query_row(params, f) stmt.query_row(params, f)
} }
@ -416,8 +416,8 @@ impl Connection {
where where
F: FnOnce(&Row) -> T, F: FnOnce(&Row) -> T,
{ {
let mut stmt = try!(self.prepare(sql)); let mut stmt = self.prepare(sql)?;
let mut rows = try!(stmt.query_named(params)); let mut rows = stmt.query_named(params)?;
rows.get_expected_row().map(|r| f(&r)) rows.get_expected_row().map(|r| f(&r))
} }
@ -454,8 +454,8 @@ impl Connection {
F: FnOnce(&Row) -> result::Result<T, E>, F: FnOnce(&Row) -> result::Result<T, E>,
E: convert::From<Error>, E: convert::From<Error>,
{ {
let mut stmt = try!(self.prepare(sql)); let mut stmt = self.prepare(sql)?;
let mut rows = try!(stmt.query(params)); let mut rows = stmt.query(params)?;
rows.get_expected_row().map_err(E::from).and_then(|r| f(&r)) rows.get_expected_row().map_err(E::from).and_then(|r| f(&r))
} }
@ -467,9 +467,9 @@ impl Connection {
/// ```rust,no_run /// ```rust,no_run
/// # use rusqlite::{Connection, Result}; /// # use rusqlite::{Connection, Result};
/// fn insert_new_people(conn: &Connection) -> Result<()> { /// fn insert_new_people(conn: &Connection) -> Result<()> {
/// let mut stmt = try!(conn.prepare("INSERT INTO People (name) VALUES (?)")); /// let mut stmt = conn.prepare("INSERT INTO People (name) VALUES (?)")?;
/// try!(stmt.execute(&["Joe Smith"])); /// stmt.execute(&["Joe Smith"])?;
/// try!(stmt.execute(&["Bob Jones"])); /// stmt.execute(&["Bob Jones"])?;
/// Ok(()) /// Ok(())
/// } /// }
/// ``` /// ```
@ -506,8 +506,8 @@ impl Connection {
/// # use rusqlite::{Connection, Result}; /// # use rusqlite::{Connection, Result};
/// # use std::path::{Path}; /// # use std::path::{Path};
/// fn load_my_extension(conn: &Connection) -> Result<()> { /// fn load_my_extension(conn: &Connection) -> Result<()> {
/// try!(conn.load_extension_enable()); /// conn.load_extension_enable()?;
/// try!(conn.load_extension(Path::new("my_sqlite_extension"), None)); /// conn.load_extension(Path::new("my_sqlite_extension"), None)?;
/// conn.load_extension_disable() /// conn.load_extension_disable()
/// } /// }
/// ``` /// ```
@ -546,7 +546,7 @@ impl Connection {
/// # use rusqlite::{Connection, Result, LoadExtensionGuard}; /// # use rusqlite::{Connection, Result, LoadExtensionGuard};
/// # use std::path::{Path}; /// # use std::path::{Path};
/// fn load_my_extension(conn: &Connection) -> Result<()> { /// fn load_my_extension(conn: &Connection) -> Result<()> {
/// let _guard = try!(LoadExtensionGuard::new(conn)); /// let _guard = LoadExtensionGuard::new(conn)?;
/// ///
/// conn.load_extension("my_sqlite_extension", None) /// conn.load_extension("my_sqlite_extension", None)
/// } /// }
@ -817,7 +817,7 @@ impl InnerConnection {
#[cfg(feature = "hooks")] #[cfg(feature = "hooks")]
fn new(db: *mut ffi::sqlite3) -> InnerConnection { fn new(db: *mut ffi::sqlite3) -> InnerConnection {
InnerConnection { InnerConnection {
db: db, db,
interrupt_lock: Arc::new(Mutex::new(db)), interrupt_lock: Arc::new(Mutex::new(db)),
free_commit_hook: None, free_commit_hook: None,
free_rollback_hook: None, free_rollback_hook: None,
@ -919,7 +919,7 @@ impl InnerConnection {
} }
fn execute_batch(&mut self, sql: &str) -> Result<()> { fn execute_batch(&mut self, sql: &str) -> Result<()> {
let c_sql = try!(str_to_cstring(sql)); let c_sql = str_to_cstring(sql)?;
unsafe { unsafe {
let r = ffi::sqlite3_exec( let r = ffi::sqlite3_exec(
self.db(), self.db(),
@ -940,11 +940,11 @@ impl InnerConnection {
#[cfg(feature = "load_extension")] #[cfg(feature = "load_extension")]
fn load_extension(&self, dylib_path: &Path, entry_point: Option<&str>) -> Result<()> { fn load_extension(&self, dylib_path: &Path, entry_point: Option<&str>) -> Result<()> {
let dylib_str = try!(path_to_cstring(dylib_path)); let dylib_str = path_to_cstring(dylib_path)?;
unsafe { unsafe {
let mut errmsg: *mut c_char = mem::uninitialized(); let mut errmsg: *mut c_char = mem::uninitialized();
let r = if let Some(entry_point) = entry_point { let r = if let Some(entry_point) = entry_point {
let c_entry = try!(str_to_cstring(entry_point)); let c_entry = str_to_cstring(entry_point)?;
ffi::sqlite3_load_extension( ffi::sqlite3_load_extension(
self.db, self.db,
dylib_str.as_ptr(), dylib_str.as_ptr(),
@ -973,7 +973,7 @@ impl InnerConnection {
return Err(error_from_sqlite_code(ffi::SQLITE_TOOBIG, None)); return Err(error_from_sqlite_code(ffi::SQLITE_TOOBIG, None));
} }
let mut c_stmt: *mut ffi::sqlite3_stmt = unsafe { mem::uninitialized() }; let mut c_stmt: *mut ffi::sqlite3_stmt = unsafe { mem::uninitialized() };
let c_sql = try!(str_to_cstring(sql)); let c_sql = str_to_cstring(sql)?;
let len_with_nul = (sql.len() + 1) as c_int; let len_with_nul = (sql.len() + 1) as c_int;
let r = unsafe { let r = unsafe {
if cfg!(feature = "unlock_notify") { if cfg!(feature = "unlock_notify") {
@ -1087,7 +1087,7 @@ mod test {
extern crate tempdir; extern crate tempdir;
use self::tempdir::TempDir; use self::tempdir::TempDir;
pub use super::*; pub use super::*;
use ffi; use crate::ffi;
pub use std::error::Error as StdError; pub use std::error::Error as StdError;
pub use std::fmt; pub use std::fmt;
@ -1578,7 +1578,7 @@ mod test {
let i_to_insert = i as i64; let i_to_insert = i as i64;
assert_eq!( assert_eq!(
insert_stmt insert_stmt
.execute(&[&i_to_insert as &dyn ToSql, &v]) .execute(&[&i_to_insert as &ToSql, &v])
.unwrap(), .unwrap(),
1 1
); );

View File

@ -2,10 +2,10 @@
use std::os::raw::c_int; use std::os::raw::c_int;
use ffi; use crate::ffi;
pub use ffi::Limit; pub use crate::ffi::Limit;
use Connection; use crate::Connection;
impl Connection { impl Connection {
/// Returns the current value of a limit. /// Returns the current value of a limit.
@ -23,8 +23,8 @@ impl Connection {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use ffi::Limit; use crate::ffi::Limit;
use Connection; use crate::Connection;
#[test] #[test]
fn test_limit() { fn test_limit() {
@ -57,13 +57,13 @@ mod test {
assert_eq!(99, db.limit(Limit::SQLITE_LIMIT_VARIABLE_NUMBER)); assert_eq!(99, db.limit(Limit::SQLITE_LIMIT_VARIABLE_NUMBER));
// SQLITE_LIMIT_TRIGGER_DEPTH was added in SQLite 3.6.18. // SQLITE_LIMIT_TRIGGER_DEPTH was added in SQLite 3.6.18.
if ::version_number() >= 3006018 { if crate::version_number() >= 3006018 {
db.set_limit(Limit::SQLITE_LIMIT_TRIGGER_DEPTH, 32); db.set_limit(Limit::SQLITE_LIMIT_TRIGGER_DEPTH, 32);
assert_eq!(32, db.limit(Limit::SQLITE_LIMIT_TRIGGER_DEPTH)); assert_eq!(32, db.limit(Limit::SQLITE_LIMIT_TRIGGER_DEPTH));
} }
// SQLITE_LIMIT_WORKER_THREADS was added in SQLite 3.8.7. // SQLITE_LIMIT_WORKER_THREADS was added in SQLite 3.8.7.
if ::version_number() >= 3008007 { if crate::version_number() >= 3008007 {
db.set_limit(Limit::SQLITE_LIMIT_WORKER_THREADS, 2); db.set_limit(Limit::SQLITE_LIMIT_WORKER_THREADS, 2);
assert_eq!(2, db.limit(Limit::SQLITE_LIMIT_WORKER_THREADS)); assert_eq!(2, db.limit(Limit::SQLITE_LIMIT_WORKER_THREADS));
} }

View File

@ -1,4 +1,4 @@
use {Connection, Result}; use crate::{Connection, Result};
/// Old name for `LoadExtensionGuard`. `SqliteLoadExtensionGuard` is deprecated. /// Old name for `LoadExtensionGuard`. `SqliteLoadExtensionGuard` is deprecated.
#[deprecated(since = "0.6.0", note = "Use LoadExtensionGuard instead")] #[deprecated(since = "0.6.0", note = "Use LoadExtensionGuard instead")]
@ -12,7 +12,7 @@ pub type SqliteLoadExtensionGuard<'conn> = LoadExtensionGuard<'conn>;
/// # use rusqlite::{Connection, Result, LoadExtensionGuard}; /// # use rusqlite::{Connection, Result, LoadExtensionGuard};
/// # use std::path::{Path}; /// # use std::path::{Path};
/// fn load_my_extension(conn: &Connection) -> Result<()> { /// fn load_my_extension(conn: &Connection) -> Result<()> {
/// let _guard = try!(LoadExtensionGuard::new(conn)); /// let _guard = LoadExtensionGuard::new(conn)?;
/// ///
/// conn.load_extension(Path::new("my_sqlite_extension"), None) /// conn.load_extension(Path::new("my_sqlite_extension"), None)
/// } /// }

View File

@ -2,7 +2,7 @@ use std::marker::PhantomData;
use std::{convert, result}; use std::{convert, result};
use super::{Error, Result, Statement}; use super::{Error, Result, Statement};
use types::{FromSql, FromSqlError, ValueRef}; use crate::types::{FromSql, FromSqlError, ValueRef};
/// An handle for the resulting rows of a query. /// An handle for the resulting rows of a query.
pub struct Rows<'stmt> { pub struct Rows<'stmt> {
@ -165,7 +165,7 @@ impl<'a, 'stmt> Row<'a, 'stmt> {
/// enabled), and the underlying SQLite column is a blob whose size is not /// enabled), and the underlying SQLite column is a blob whose size is not
/// 16 bytes, `Error::InvalidColumnType` will also be returned. /// 16 bytes, `Error::InvalidColumnType` will also be returned.
pub fn get_checked<I: RowIndex, T: FromSql>(&self, idx: I) -> Result<T> { pub fn get_checked<I: RowIndex, T: FromSql>(&self, idx: I) -> Result<T> {
let idx = try!(idx.idx(self.stmt)); let idx = idx.idx(self.stmt)?;
let value = self.stmt.value_ref(idx); let value = self.stmt.value_ref(idx);
FromSql::column_result(value).map_err(|err| match err { FromSql::column_result(value).map_err(|err| match err {
FromSqlError::InvalidType => Error::InvalidColumnType(idx, value.data_type()), FromSqlError::InvalidType => Error::InvalidColumnType(idx, value.data_type()),

View File

@ -11,9 +11,9 @@ use super::str_to_cstring;
use super::{ use super::{
AndThenRows, Connection, Error, MappedRows, RawStatement, Result, Row, Rows, ValueRef, AndThenRows, Connection, Error, MappedRows, RawStatement, Result, Row, Rows, ValueRef,
}; };
use types::{ToSql, ToSqlOutput}; use crate::types::{ToSql, ToSqlOutput};
#[cfg(feature = "array")] #[cfg(feature = "array")]
use vtab::array::{free_array, ARRAY_TYPE}; use crate::vtab::array::{free_array, ARRAY_TYPE};
/// A prepared statement. /// A prepared statement.
pub struct Statement<'conn> { pub struct Statement<'conn> {
@ -70,10 +70,10 @@ impl<'conn> Statement<'conn> {
/// ```rust,no_run /// ```rust,no_run
/// # use rusqlite::{Connection, Result}; /// # use rusqlite::{Connection, Result};
/// fn update_rows(conn: &Connection) -> Result<()> { /// fn update_rows(conn: &Connection) -> Result<()> {
/// let mut stmt = try!(conn.prepare("UPDATE foo SET bar = 'baz' WHERE qux = ?")); /// let mut stmt = conn.prepare("UPDATE foo SET bar = 'baz' WHERE qux = ?")?;
/// ///
/// try!(stmt.execute(&[1i32])); /// stmt.execute(&[1i32])?;
/// try!(stmt.execute(&[2i32])); /// stmt.execute(&[2i32])?;
/// ///
/// Ok(()) /// Ok(())
/// } /// }
@ -89,7 +89,7 @@ impl<'conn> Statement<'conn> {
P: IntoIterator, P: IntoIterator,
P::Item: ToSql, P::Item: ToSql,
{ {
try!(self.bind_parameters(params)); self.bind_parameters(params)?;
self.execute_with_bound_parameters() self.execute_with_bound_parameters()
} }
@ -107,7 +107,7 @@ impl<'conn> Statement<'conn> {
/// ```rust,no_run /// ```rust,no_run
/// # use rusqlite::{Connection, Result}; /// # use rusqlite::{Connection, Result};
/// fn insert(conn: &Connection) -> Result<usize> { /// fn insert(conn: &Connection) -> Result<usize> {
/// let mut stmt = try!(conn.prepare("INSERT INTO test (name) VALUES (:name)")); /// let mut stmt = conn.prepare("INSERT INTO test (name) VALUES (:name)")?;
/// stmt.execute_named(&[(":name", &"one")]) /// stmt.execute_named(&[(":name", &"one")])
/// } /// }
/// ``` /// ```
@ -118,7 +118,7 @@ impl<'conn> Statement<'conn> {
/// returns rows (in which case `query` should be used instead), or the /// returns rows (in which case `query` should be used instead), or the
/// underling SQLite call fails. /// underling SQLite call fails.
pub fn execute_named(&mut self, params: &[(&str, &ToSql)]) -> Result<usize> { pub fn execute_named(&mut self, params: &[(&str, &ToSql)]) -> Result<usize> {
try!(self.bind_parameters_named(params)); self.bind_parameters_named(params)?;
self.execute_with_bound_parameters() self.execute_with_bound_parameters()
} }
@ -140,7 +140,7 @@ impl<'conn> Statement<'conn> {
P: IntoIterator, P: IntoIterator,
P::Item: ToSql, P::Item: ToSql,
{ {
let changes = try!(self.execute(params)); let changes = self.execute(params)?;
match changes { match changes {
1 => Ok(self.conn.last_insert_rowid()), 1 => Ok(self.conn.last_insert_rowid()),
_ => Err(Error::StatementChangedRows(changes)), _ => Err(Error::StatementChangedRows(changes)),
@ -159,12 +159,12 @@ impl<'conn> Statement<'conn> {
/// ```rust,no_run /// ```rust,no_run
/// # use rusqlite::{Connection, Result, NO_PARAMS}; /// # use rusqlite::{Connection, Result, NO_PARAMS};
/// fn get_names(conn: &Connection) -> Result<Vec<String>> { /// fn get_names(conn: &Connection) -> Result<Vec<String>> {
/// let mut stmt = try!(conn.prepare("SELECT name FROM people")); /// let mut stmt = conn.prepare("SELECT name FROM people")?;
/// let mut rows = try!(stmt.query(NO_PARAMS)); /// let mut rows = stmt.query(NO_PARAMS)?;
/// ///
/// let mut names = Vec::new(); /// let mut names = Vec::new();
/// while let Some(result_row) = rows.next() { /// while let Some(result_row) = rows.next() {
/// let row = try!(result_row); /// let row = result_row?;
/// names.push(row.get(0)); /// names.push(row.get(0));
/// } /// }
/// ///
@ -180,8 +180,8 @@ impl<'conn> Statement<'conn> {
P: IntoIterator, P: IntoIterator,
P::Item: ToSql, P::Item: ToSql,
{ {
try!(self.check_readonly()); self.check_readonly()?;
try!(self.bind_parameters(params)); self.bind_parameters(params)?;
Ok(Rows::new(self)) Ok(Rows::new(self))
} }
@ -196,8 +196,8 @@ impl<'conn> Statement<'conn> {
/// ```rust,no_run /// ```rust,no_run
/// # use rusqlite::{Connection, Result}; /// # use rusqlite::{Connection, Result};
/// fn query(conn: &Connection) -> Result<()> { /// fn query(conn: &Connection) -> Result<()> {
/// let mut stmt = try!(conn.prepare("SELECT * FROM test where name = :name")); /// let mut stmt = conn.prepare("SELECT * FROM test where name = :name")?;
/// let mut rows = try!(stmt.query_named(&[(":name", &"one")])); /// let mut rows = stmt.query_named(&[(":name", &"one")])?;
/// while let Some(row) = rows.next() { /// while let Some(row) = rows.next() {
/// // ... /// // ...
/// } /// }
@ -209,8 +209,8 @@ impl<'conn> Statement<'conn> {
/// ///
/// Will return `Err` if binding parameters fails. /// Will return `Err` if binding parameters fails.
pub fn query_named<'a>(&'a mut self, params: &[(&str, &ToSql)]) -> Result<Rows<'a>> { pub fn query_named<'a>(&'a mut self, params: &[(&str, &ToSql)]) -> Result<Rows<'a>> {
try!(self.check_readonly()); self.check_readonly()?;
try!(self.bind_parameters_named(params)); self.bind_parameters_named(params)?;
Ok(Rows::new(self)) Ok(Rows::new(self))
} }
@ -222,12 +222,12 @@ impl<'conn> Statement<'conn> {
/// ```rust,no_run /// ```rust,no_run
/// # use rusqlite::{Connection, Result, NO_PARAMS}; /// # use rusqlite::{Connection, Result, NO_PARAMS};
/// fn get_names(conn: &Connection) -> Result<Vec<String>> { /// fn get_names(conn: &Connection) -> Result<Vec<String>> {
/// let mut stmt = try!(conn.prepare("SELECT name FROM people")); /// let mut stmt = conn.prepare("SELECT name FROM people")?;
/// let rows = try!(stmt.query_map(NO_PARAMS, |row| row.get(0))); /// let rows = stmt.query_map(NO_PARAMS, |row| row.get(0))?;
/// ///
/// let mut names = Vec::new(); /// let mut names = Vec::new();
/// for name_result in rows { /// for name_result in rows {
/// names.push(try!(name_result)); /// names.push(name_result?);
/// } /// }
/// ///
/// Ok(names) /// Ok(names)
@ -259,12 +259,12 @@ impl<'conn> Statement<'conn> {
/// ```rust,no_run /// ```rust,no_run
/// # use rusqlite::{Connection, Result}; /// # use rusqlite::{Connection, Result};
/// fn get_names(conn: &Connection) -> Result<Vec<String>> { /// fn get_names(conn: &Connection) -> Result<Vec<String>> {
/// let mut stmt = try!(conn.prepare("SELECT name FROM people WHERE id = :id")); /// let mut stmt = conn.prepare("SELECT name FROM people WHERE id = :id")?;
/// let rows = try!(stmt.query_map_named(&[(":id", &"one")], |row| row.get(0))); /// let rows = stmt.query_map_named(&[(":id", &"one")], |row| row.get(0))?;
/// ///
/// let mut names = Vec::new(); /// let mut names = Vec::new();
/// for name_result in rows { /// for name_result in rows {
/// names.push(try!(name_result)); /// names.push(name_result?);
/// } /// }
/// ///
/// Ok(names) /// Ok(names)
@ -330,13 +330,13 @@ impl<'conn> Statement<'conn> {
/// } /// }
/// ///
/// fn get_names(conn: &Connection) -> Result<Vec<Person>> { /// fn get_names(conn: &Connection) -> Result<Vec<Person>> {
/// let mut stmt = try!(conn.prepare("SELECT name FROM people WHERE id = :id")); /// let mut stmt = conn.prepare("SELECT name FROM people WHERE id = :id")?;
/// let rows = /// let rows =
/// try!(stmt.query_and_then_named(&[(":id", &"one")], |row| name_to_person(row.get(0)))); /// stmt.query_and_then_named(&[(":id", &"one")], |row| name_to_person(row.get(0)))?;
/// ///
/// let mut persons = Vec::new(); /// let mut persons = Vec::new();
/// for person_result in rows { /// for person_result in rows {
/// persons.push(try!(person_result)); /// persons.push(person_result?);
/// } /// }
/// ///
/// Ok(persons) /// Ok(persons)
@ -366,7 +366,7 @@ impl<'conn> Statement<'conn> {
P: IntoIterator, P: IntoIterator,
P::Item: ToSql, P::Item: ToSql,
{ {
let mut rows = try!(self.query(params)); let mut rows = self.query(params)?;
let exists = { let exists = {
match rows.next() { match rows.next() {
Some(_) => true, Some(_) => true,
@ -391,7 +391,7 @@ impl<'conn> Statement<'conn> {
P::Item: ToSql, P::Item: ToSql,
F: FnOnce(&Row) -> T, F: FnOnce(&Row) -> T,
{ {
let mut rows = try!(self.query(params)); let mut rows = self.query(params)?;
rows.get_expected_row().map(|r| f(&r)) rows.get_expected_row().map(|r| f(&r))
} }
@ -415,7 +415,7 @@ impl<'conn> Statement<'conn> {
/// Will return Err if `name` is invalid. Will return Ok(None) if the name /// Will return Err if `name` is invalid. Will return Ok(None) if the name
/// is valid but not a bound parameter of this statement. /// is valid but not a bound parameter of this statement.
pub fn parameter_index(&self, name: &str) -> Result<Option<usize>> { pub fn parameter_index(&self, name: &str) -> Result<Option<usize>> {
let c_name = try!(str_to_cstring(name)); let c_name = str_to_cstring(name)?;
Ok(self.stmt.bind_parameter_index(&c_name)) Ok(self.stmt.bind_parameter_index(&c_name))
} }
@ -431,7 +431,7 @@ impl<'conn> Statement<'conn> {
if index > expected { if index > expected {
break; break;
} }
try!(self.bind_parameter(&p, index)); self.bind_parameter(&p, index)?;
} }
assert_eq!( assert_eq!(
index, expected, index, expected,
@ -444,8 +444,8 @@ impl<'conn> Statement<'conn> {
fn bind_parameters_named(&mut self, params: &[(&str, &ToSql)]) -> Result<()> { fn bind_parameters_named(&mut self, params: &[(&str, &ToSql)]) -> Result<()> {
for &(name, value) in params { for &(name, value) in params {
if let Some(i) = try!(self.parameter_index(name)) { if let Some(i) = self.parameter_index(name)? {
try!(self.bind_parameter(value, i)); self.bind_parameter(value, i)?;
} else { } else {
return Err(Error::InvalidParameterName(name.into())); return Err(Error::InvalidParameterName(name.into()));
} }
@ -454,7 +454,7 @@ impl<'conn> Statement<'conn> {
} }
fn bind_parameter(&self, param: &ToSql, col: usize) -> Result<()> { fn bind_parameter(&self, param: &ToSql, col: usize) -> Result<()> {
let value = try!(param.to_sql()); let value = param.to_sql()?;
let ptr = unsafe { self.stmt.ptr() }; let ptr = unsafe { self.stmt.ptr() };
let value = match value { let value = match value {
@ -489,7 +489,7 @@ impl<'conn> Statement<'conn> {
if length > ::std::i32::MAX as usize { if length > ::std::i32::MAX as usize {
ffi::SQLITE_TOOBIG ffi::SQLITE_TOOBIG
} else { } else {
let c_str = try!(str_to_cstring(s)); let c_str = str_to_cstring(s)?;
let destructor = if length > 0 { let destructor = if length > 0 {
ffi::SQLITE_TRANSIENT() ffi::SQLITE_TRANSIENT()
} else { } else {
@ -673,7 +673,7 @@ impl<'conn> Statement<'conn> {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use {Connection, Error, Result, NO_PARAMS}; use crate::{Connection, Error, Result, NO_PARAMS};
#[test] #[test]
fn test_execute_named() { fn test_execute_named() {

View File

@ -7,8 +7,8 @@ use std::ptr;
use std::time::Duration; use std::time::Duration;
use super::ffi; use super::ffi;
use error::error_from_sqlite_code; use crate::error::error_from_sqlite_code;
use {Connection, Result}; use crate::{Connection, Result};
/// Set up the process-wide SQLite error logging callback. /// Set up the process-wide SQLite error logging callback.
/// This function is marked unsafe for two reasons: /// This function is marked unsafe for two reasons:
@ -124,7 +124,7 @@ mod test {
use std::sync::Mutex; use std::sync::Mutex;
use std::time::Duration; use std::time::Duration;
use Connection; use crate::Connection;
#[test] #[test]
fn test_trace() { fn test_trace() {

View File

@ -1,5 +1,5 @@
use std::ops::Deref; use std::ops::Deref;
use {Connection, Result}; use crate::{Connection, Result};
/// Old name for `TransactionBehavior`. `SqliteTransactionBehavior` is /// Old name for `TransactionBehavior`. `SqliteTransactionBehavior` is
/// deprecated. /// deprecated.
@ -51,10 +51,10 @@ pub type SqliteTransaction<'conn> = Transaction<'conn>;
/// # fn do_queries_part_1(_conn: &Connection) -> Result<()> { Ok(()) } /// # fn do_queries_part_1(_conn: &Connection) -> Result<()> { Ok(()) }
/// # fn do_queries_part_2(_conn: &Connection) -> Result<()> { Ok(()) } /// # fn do_queries_part_2(_conn: &Connection) -> Result<()> { Ok(()) }
/// fn perform_queries(conn: &mut Connection) -> Result<()> { /// fn perform_queries(conn: &mut Connection) -> Result<()> {
/// let tx = try!(conn.transaction()); /// let tx = conn.transaction()?;
/// ///
/// try!(do_queries_part_1(&tx)); // tx causes rollback if this fails /// do_queries_part_1(&tx)?; // tx causes rollback if this fails
/// try!(do_queries_part_2(&tx)); // tx causes rollback if this fails /// do_queries_part_2(&tx)?; // tx causes rollback if this fails
/// ///
/// tx.commit() /// tx.commit()
/// } /// }
@ -79,10 +79,10 @@ pub struct Transaction<'conn> {
/// # fn do_queries_part_1(_conn: &Connection) -> Result<()> { Ok(()) } /// # fn do_queries_part_1(_conn: &Connection) -> Result<()> { Ok(()) }
/// # fn do_queries_part_2(_conn: &Connection) -> Result<()> { Ok(()) } /// # fn do_queries_part_2(_conn: &Connection) -> Result<()> { Ok(()) }
/// fn perform_queries(conn: &mut Connection) -> Result<()> { /// fn perform_queries(conn: &mut Connection) -> Result<()> {
/// let sp = try!(conn.savepoint()); /// let sp = conn.savepoint()?;
/// ///
/// try!(do_queries_part_1(&sp)); // sp causes rollback if this fails /// do_queries_part_1(&sp)?; // sp causes rollback if this fails
/// try!(do_queries_part_2(&sp)); // sp causes rollback if this fails /// do_queries_part_2(&sp)?; // sp causes rollback if this fails
/// ///
/// sp.commit() /// sp.commit()
/// } /// }
@ -127,12 +127,12 @@ impl<'conn> Transaction<'conn> {
/// # use rusqlite::{Connection, Result}; /// # use rusqlite::{Connection, Result};
/// # fn perform_queries_part_1_succeeds(_conn: &Connection) -> bool { true } /// # fn perform_queries_part_1_succeeds(_conn: &Connection) -> bool { true }
/// fn perform_queries(conn: &mut Connection) -> Result<()> { /// fn perform_queries(conn: &mut Connection) -> Result<()> {
/// let mut tx = try!(conn.transaction()); /// let mut tx = conn.transaction()?;
/// ///
/// { /// {
/// let sp = try!(tx.savepoint()); /// let sp = tx.savepoint()?;
/// if perform_queries_part_1_succeeds(&sp) { /// if perform_queries_part_1_succeeds(&sp) {
/// try!(sp.commit()); /// sp.commit()?;
/// } /// }
/// // otherwise, sp will rollback /// // otherwise, sp will rollback
/// } /// }
@ -345,10 +345,10 @@ impl Connection {
/// # fn do_queries_part_1(_conn: &Connection) -> Result<()> { Ok(()) } /// # fn do_queries_part_1(_conn: &Connection) -> Result<()> { Ok(()) }
/// # fn do_queries_part_2(_conn: &Connection) -> Result<()> { Ok(()) } /// # fn do_queries_part_2(_conn: &Connection) -> Result<()> { Ok(()) }
/// fn perform_queries(conn: &mut Connection) -> Result<()> { /// fn perform_queries(conn: &mut Connection) -> Result<()> {
/// let tx = try!(conn.transaction()); /// let tx = conn.transaction()?;
/// ///
/// try!(do_queries_part_1(&tx)); // tx causes rollback if this fails /// do_queries_part_1(&tx)?; // tx causes rollback if this fails
/// try!(do_queries_part_2(&tx)); // tx causes rollback if this fails /// do_queries_part_2(&tx)?; // tx causes rollback if this fails
/// ///
/// tx.commit() /// tx.commit()
/// } /// }
@ -388,10 +388,10 @@ impl Connection {
/// # fn do_queries_part_1(_conn: &Connection) -> Result<()> { Ok(()) } /// # fn do_queries_part_1(_conn: &Connection) -> Result<()> { Ok(()) }
/// # fn do_queries_part_2(_conn: &Connection) -> Result<()> { Ok(()) } /// # fn do_queries_part_2(_conn: &Connection) -> Result<()> { Ok(()) }
/// fn perform_queries(conn: &mut Connection) -> Result<()> { /// fn perform_queries(conn: &mut Connection) -> Result<()> {
/// let sp = try!(conn.savepoint()); /// let sp = conn.savepoint()?;
/// ///
/// try!(do_queries_part_1(&sp)); // sp causes rollback if this fails /// do_queries_part_1(&sp)?; // sp causes rollback if this fails
/// try!(do_queries_part_2(&sp)); // sp causes rollback if this fails /// do_queries_part_2(&sp)?; // sp causes rollback if this fails
/// ///
/// sp.commit() /// sp.commit()
/// } /// }
@ -419,7 +419,7 @@ impl Connection {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use super::DropBehavior; use super::DropBehavior;
use {Connection, NO_PARAMS}; use crate::{Connection, NO_PARAMS};
fn checked_memory_handle() -> Connection { fn checked_memory_handle() -> Connection {
let db = Connection::open_in_memory().unwrap(); let db = Connection::open_in_memory().unwrap();

View File

@ -5,8 +5,8 @@ use std::borrow::Cow;
use self::chrono::{DateTime, Local, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Utc}; use self::chrono::{DateTime, Local, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Utc};
use types::{FromSql, FromSqlError, FromSqlResult, ToSql, ToSqlOutput, ValueRef}; use crate::types::{FromSql, FromSqlError, FromSqlResult, ToSql, ToSqlOutput, ValueRef};
use Result; use crate::Result;
/// ISO 8601 calendar date without timezone => "YYYY-MM-DD" /// ISO 8601 calendar date without timezone => "YYYY-MM-DD"
impl ToSql for NaiveDate { impl ToSql for NaiveDate {
@ -95,7 +95,7 @@ impl FromSql for DateTime<Utc> {
fn column_result(value: ValueRef) -> FromSqlResult<Self> { fn column_result(value: ValueRef) -> FromSqlResult<Self> {
{ {
// Try to parse value as rfc3339 first. // Try to parse value as rfc3339 first.
let s = try!(value.as_str()); let s = value.as_str()?;
// If timestamp looks space-separated, make a copy and replace it with 'T'. // If timestamp looks space-separated, make a copy and replace it with 'T'.
let s = if s.len() >= 11 && s.as_bytes()[10] == b' ' { let s = if s.len() >= 11 && s.as_bytes()[10] == b' ' {
@ -122,7 +122,7 @@ impl FromSql for DateTime<Utc> {
/// RFC3339 ("YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM") into `DateTime<Local>`. /// RFC3339 ("YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM") into `DateTime<Local>`.
impl FromSql for DateTime<Local> { impl FromSql for DateTime<Local> {
fn column_result(value: ValueRef) -> FromSqlResult<Self> { fn column_result(value: ValueRef) -> FromSqlResult<Self> {
let utc_dt = try!(DateTime::<Utc>::column_result(value)); let utc_dt = DateTime::<Utc>::column_result(value)?;
Ok(utc_dt.with_timezone(&Local)) Ok(utc_dt.with_timezone(&Local))
} }
} }
@ -132,7 +132,7 @@ mod test {
use super::chrono::{ use super::chrono::{
DateTime, Duration, Local, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Utc, DateTime, Duration, Local, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Utc,
}; };
use {Connection, NO_PARAMS}; use crate::{Connection, NO_PARAMS};
fn checked_memory_handle() -> Connection { fn checked_memory_handle() -> Connection {
let db = Connection::open_in_memory().unwrap(); let db = Connection::open_in_memory().unwrap();

View File

@ -181,7 +181,7 @@ impl FromSql for Value {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use super::FromSql; use super::FromSql;
use {Connection, Error}; use crate::{Connection, Error};
fn checked_memory_handle() -> Connection { fn checked_memory_handle() -> Connection {
Connection::open_in_memory().unwrap() Connection::open_in_memory().unwrap()

View File

@ -116,7 +116,7 @@ mod test {
use super::Value; use super::Value;
use std::f64::EPSILON; use std::f64::EPSILON;
use std::os::raw::{c_double, c_int}; use std::os::raw::{c_double, c_int};
use {Connection, Error, NO_PARAMS}; use crate::{Connection, Error, NO_PARAMS};
fn checked_memory_handle() -> Connection { fn checked_memory_handle() -> Connection {
let db = Connection::open_in_memory().unwrap(); let db = Connection::open_in_memory().unwrap();

View File

@ -3,8 +3,8 @@ extern crate serde_json;
use self::serde_json::Value; use self::serde_json::Value;
use types::{FromSql, FromSqlError, FromSqlResult, ToSql, ToSqlOutput, ValueRef}; use crate::types::{FromSql, FromSqlError, FromSqlResult, ToSql, ToSqlOutput, ValueRef};
use Result; use crate::Result;
/// Serialize JSON `Value` to text. /// Serialize JSON `Value` to text.
impl ToSql for Value { impl ToSql for Value {
@ -28,8 +28,8 @@ impl FromSql for Value {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use super::serde_json; use super::serde_json;
use types::ToSql; use crate::types::ToSql;
use {Connection, NO_PARAMS}; use crate::{Connection, NO_PARAMS};
fn checked_memory_handle() -> Connection { fn checked_memory_handle() -> Connection {
let db = Connection::open_in_memory().unwrap(); let db = Connection::open_in_memory().unwrap();

View File

@ -1,7 +1,7 @@
extern crate time; extern crate time;
use types::{FromSql, FromSqlError, FromSqlResult, ToSql, ToSqlOutput, ValueRef}; use crate::types::{FromSql, FromSqlError, FromSqlResult, ToSql, ToSqlOutput, ValueRef};
use Result; use crate::Result;
const SQLITE_DATETIME_FMT: &str = "%Y-%m-%dT%H:%M:%S.%fZ"; const SQLITE_DATETIME_FMT: &str = "%Y-%m-%dT%H:%M:%S.%fZ";
const SQLITE_DATETIME_FMT_LEGACY: &str = "%Y-%m-%d %H:%M:%S:%f %Z"; const SQLITE_DATETIME_FMT_LEGACY: &str = "%Y-%m-%d %H:%M:%S:%f %Z";
@ -33,7 +33,7 @@ impl FromSql for time::Timespec {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use super::time; use super::time;
use {Connection, NO_PARAMS}; use crate::{Connection, NO_PARAMS};
fn checked_memory_handle() -> Connection { fn checked_memory_handle() -> Connection {
let db = Connection::open_in_memory().unwrap(); let db = Connection::open_in_memory().unwrap();

View File

@ -1,8 +1,8 @@
use super::{Null, Value, ValueRef}; use super::{Null, Value, ValueRef};
use std::borrow::Cow; use std::borrow::Cow;
#[cfg(feature = "array")] #[cfg(feature = "array")]
use vtab::array::Array; use crate::vtab::array::Array;
use Result; use crate::Result;
/// `ToSqlOutput` represents the possible output types for implementors of the /// `ToSqlOutput` represents the possible output types for implementors of the
/// `ToSql` trait. /// `ToSql` trait.
@ -208,7 +208,7 @@ mod test {
#[test] #[test]
fn test_i128() { fn test_i128() {
use std::i128; use std::i128;
use {Connection, NO_PARAMS}; use crate::{Connection, NO_PARAMS};
let db = Connection::open_in_memory().unwrap(); let db = Connection::open_in_memory().unwrap();
db.execute_batch("CREATE TABLE foo (i128 BLOB, desc TEXT)") db.execute_batch("CREATE TABLE foo (i128 BLOB, desc TEXT)")
.unwrap(); .unwrap();

View File

@ -1,5 +1,5 @@
use super::{Type, Value}; use super::{Type, Value};
use types::{FromSqlError, FromSqlResult}; use crate::types::{FromSqlError, FromSqlResult};
/// A non-owning [dynamic type value](http://sqlite.org/datatype3.html). Typically the /// A non-owning [dynamic type value](http://sqlite.org/datatype3.html). Typically the
/// memory backing this value is owned by SQLite. /// memory backing this value is owned by SQLite.

View File

@ -6,7 +6,7 @@ use std::os::raw::c_void;
#[cfg(feature = "unlock_notify")] #[cfg(feature = "unlock_notify")]
use std::sync::{Condvar, Mutex}; use std::sync::{Condvar, Mutex};
use ffi; use crate::ffi;
#[cfg(feature = "unlock_notify")] #[cfg(feature = "unlock_notify")]
struct UnlockNotification { struct UnlockNotification {
@ -102,7 +102,7 @@ mod test {
use std::sync::mpsc::sync_channel; use std::sync::mpsc::sync_channel;
use std::thread; use std::thread;
use std::time; use std::time;
use {Connection, OpenFlags, Result, Transaction, TransactionBehavior, NO_PARAMS}; use crate::{Connection, OpenFlags, Result, Transaction, TransactionBehavior, NO_PARAMS};
#[test] #[test]
fn test_unlock_notify() { fn test_unlock_notify() {

View File

@ -1,4 +1,4 @@
use ffi; use crate::ffi;
use std::ffi::CStr; use std::ffi::CStr;
/// Returns the SQLite version as an integer; e.g., `3016002` for version /// Returns the SQLite version as an integer; e.g., `3016002` for version

View File

@ -5,13 +5,13 @@ use std::default::Default;
use std::os::raw::{c_char, c_int, c_void}; use std::os::raw::{c_char, c_int, c_void};
use std::rc::Rc; use std::rc::Rc;
use ffi; use crate::ffi;
use types::{ToSql, ToSqlOutput, Value}; use crate::types::{ToSql, ToSqlOutput, Value};
use vtab::{ use crate::vtab::{
eponymous_only_module, Context, IndexConstraintOp, IndexInfo, Module, VTab, VTabConnection, eponymous_only_module, Context, IndexConstraintOp, IndexInfo, Module, VTab, VTabConnection,
VTabCursor, Values, VTabCursor, Values,
}; };
use {Connection, Result}; use crate::{Connection, Result};
// http://sqlite.org/bindptr.html // http://sqlite.org/bindptr.html
@ -131,7 +131,7 @@ impl ArrayTabCursor {
impl VTabCursor for ArrayTabCursor { impl VTabCursor for ArrayTabCursor {
fn filter(&mut self, idx_num: c_int, _idx_str: Option<&str>, args: &Values) -> Result<()> { fn filter(&mut self, idx_num: c_int, _idx_str: Option<&str>, args: &Values) -> Result<()> {
if idx_num > 0 { if idx_num > 0 {
self.ptr = try!(args.get_array(0)); self.ptr = args.get_array(0)?;
} else { } else {
self.ptr = None; self.ptr = None;
} }
@ -170,9 +170,9 @@ impl VTabCursor for ArrayTabCursor {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use std::rc::Rc; use std::rc::Rc;
use types::Value; use crate::types::Value;
use vtab::array; use crate::vtab::array;
use Connection; use crate::Connection;
#[test] #[test]
fn test_array_module() { fn test_array_module() {

View File

@ -8,13 +8,13 @@ use std::path::Path;
use std::result; use std::result;
use std::str; use std::str;
use ffi; use crate::ffi;
use types::Null; use crate::types::Null;
use vtab::{ use crate::vtab::{
dequote, escape_double_quote, parse_boolean, read_only_module, Context, CreateVTab, IndexInfo, dequote, escape_double_quote, parse_boolean, read_only_module, Context, CreateVTab, IndexInfo,
Module, VTab, VTabConnection, VTabCursor, Values, Module, VTab, VTabConnection, VTabCursor, Values,
}; };
use {Connection, Error, Result}; use crate::{Connection, Error, Result};
/// Register the "csv" module. /// Register the "csv" module.
/// ```sql /// ```sql
@ -60,7 +60,7 @@ impl CSVTab {
} }
fn parameter(c_slice: &[u8]) -> Result<(&str, &str)> { fn parameter(c_slice: &[u8]) -> Result<(&str, &str)> {
let arg = try!(str::from_utf8(c_slice)).trim(); let arg = str::from_utf8(c_slice)?.trim();
let mut split = arg.split('='); let mut split = arg.split('=');
if let Some(key) = split.next() { if let Some(key) = split.next() {
if let Some(value) = split.next() { if let Some(value) = split.next() {
@ -107,7 +107,7 @@ impl VTab for CSVTab {
let args = &args[3..]; let args = &args[3..];
for c_slice in args { for c_slice in args {
let (param, value) = try!(CSVTab::parameter(c_slice)); let (param, value) = CSVTab::parameter(c_slice)?;
match param { match param {
"filename" => { "filename" => {
if !Path::new(value).exists() { if !Path::new(value).exists() {
@ -189,10 +189,10 @@ impl VTab for CSVTab {
let mut cols: Vec<String> = Vec::new(); let mut cols: Vec<String> = Vec::new();
if vtab.has_headers || (n_col.is_none() && schema.is_none()) { if vtab.has_headers || (n_col.is_none() && schema.is_none()) {
let mut reader = try!(vtab.reader()); let mut reader = vtab.reader()?;
if vtab.has_headers { if vtab.has_headers {
{ {
let headers = try!(reader.headers()); let headers = reader.headers()?;
// headers ignored if cols is not empty // headers ignored if cols is not empty
if n_col.is_none() && schema.is_none() { if n_col.is_none() && schema.is_none() {
cols = headers cols = headers
@ -204,7 +204,7 @@ impl VTab for CSVTab {
vtab.offset_first_row = reader.position().clone(); vtab.offset_first_row = reader.position().clone();
} else { } else {
let mut record = csv::ByteRecord::new(); let mut record = csv::ByteRecord::new();
if try!(reader.read_byte_record(&mut record)) { if reader.read_byte_record(&mut record)? {
for (i, _) in record.iter().enumerate() { for (i, _) in record.iter().enumerate() {
cols.push(format!("c{}", i)); cols.push(format!("c{}", i));
} }
@ -245,7 +245,7 @@ impl VTab for CSVTab {
} }
fn open(&self) -> Result<CSVTabCursor> { fn open(&self) -> Result<CSVTabCursor> {
Ok(CSVTabCursor::new(try!(self.reader()))) Ok(CSVTabCursor::new(self.reader()?))
} }
} }
@ -288,7 +288,7 @@ impl VTabCursor for CSVTabCursor {
fn filter(&mut self, _idx_num: c_int, _idx_str: Option<&str>, _args: &Values) -> Result<()> { fn filter(&mut self, _idx_num: c_int, _idx_str: Option<&str>, _args: &Values) -> Result<()> {
{ {
let offset_first_row = self.vtab().offset_first_row.clone(); let offset_first_row = self.vtab().offset_first_row.clone();
try!(self.reader.seek(offset_first_row)); self.reader.seek(offset_first_row)?;
} }
self.row_number = 0; self.row_number = 0;
self.next() self.next()
@ -301,7 +301,7 @@ impl VTabCursor for CSVTabCursor {
return Ok(()); return Ok(());
} }
self.eof = !try!(self.reader.read_record(&mut self.cols)); self.eof = !self.reader.read_record(&mut self.cols)?;
} }
self.row_number += 1; self.row_number += 1;
@ -340,8 +340,8 @@ impl From<csv::Error> for Error {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use vtab::csvtab; use crate::vtab::csvtab;
use {Connection, Result, NO_PARAMS}; use crate::{Connection, Result, NO_PARAMS};
#[test] #[test]
fn test_csv_module() { fn test_csv_module() {

View File

@ -17,12 +17,12 @@ use std::os::raw::{c_char, c_int, c_void};
use std::ptr; use std::ptr;
use std::slice; use std::slice;
use context::set_result; use crate::context::set_result;
use error::error_from_sqlite_code; use crate::error::error_from_sqlite_code;
use ffi; use crate::ffi;
pub use ffi::{sqlite3_vtab, sqlite3_vtab_cursor}; pub use crate::ffi::{sqlite3_vtab, sqlite3_vtab_cursor};
use types::{FromSql, FromSqlError, ToSql, ValueRef}; use crate::types::{FromSql, FromSqlError, ToSql, ValueRef};
use {str_to_cstring, Connection, Error, InnerConnection, Result}; use crate::{str_to_cstring, Connection, Error, InnerConnection, Result};
// let conn: Connection = ...; // let conn: Connection = ...;
// let mod: Module = ...; // VTab builder // let mod: Module = ...; // VTab builder
@ -474,7 +474,7 @@ impl<'a> Values<'a> {
// So it seems not possible to enhance `ValueRef::from_value`. // So it seems not possible to enhance `ValueRef::from_value`.
#[cfg(feature = "array")] #[cfg(feature = "array")]
pub(crate) fn get_array(&self, idx: usize) -> Result<Option<array::Array>> { pub(crate) fn get_array(&self, idx: usize) -> Result<Option<array::Array>> {
use types::Value; use crate::types::Value;
let arg = self.args[idx]; let arg = self.args[idx];
let ptr = unsafe { ffi::sqlite3_value_pointer(arg, array::ARRAY_TYPE) }; let ptr = unsafe { ffi::sqlite3_value_pointer(arg, array::ARRAY_TYPE) };
if ptr.is_null() { if ptr.is_null() {
@ -544,7 +544,7 @@ impl InnerConnection {
module: &Module<T>, module: &Module<T>,
aux: Option<T::Aux>, aux: Option<T::Aux>,
) -> Result<()> { ) -> Result<()> {
let c_name = try!(str_to_cstring(module_name)); let c_name = str_to_cstring(module_name)?;
let r = match aux { let r = match aux {
Some(aux) => { Some(aux) => {
let boxed_aux: *mut T::Aux = Box::into_raw(Box::new(aux)); let boxed_aux: *mut T::Aux = Box::into_raw(Box::new(aux));

View File

@ -4,13 +4,13 @@
use std::default::Default; use std::default::Default;
use std::os::raw::c_int; use std::os::raw::c_int;
use ffi; use crate::ffi;
use types::Type; use crate::types::Type;
use vtab::{ use crate::vtab::{
eponymous_only_module, Context, IndexConstraintOp, IndexInfo, Module, VTab, VTabConnection, eponymous_only_module, Context, IndexConstraintOp, IndexInfo, Module, VTab, VTabConnection,
VTabCursor, Values, VTabCursor, Values,
}; };
use {Connection, Result}; use crate::{Connection, Result};
/// Register the "generate_series" module. /// Register the "generate_series" module.
pub fn load_module(conn: &Connection) -> Result<()> { pub fn load_module(conn: &Connection) -> Result<()> {
@ -188,19 +188,19 @@ impl VTabCursor for SeriesTabCursor {
let idx_num = QueryPlanFlags::from_bits_truncate(idx_num); let idx_num = QueryPlanFlags::from_bits_truncate(idx_num);
let mut i = 0; let mut i = 0;
if idx_num.contains(QueryPlanFlags::START) { if idx_num.contains(QueryPlanFlags::START) {
self.min_value = try!(args.get(i)); self.min_value = args.get(i)?;
i += 1; i += 1;
} else { } else {
self.min_value = 0; self.min_value = 0;
} }
if idx_num.contains(QueryPlanFlags::STOP) { if idx_num.contains(QueryPlanFlags::STOP) {
self.max_value = try!(args.get(i)); self.max_value = args.get(i)?;
i += 1; i += 1;
} else { } else {
self.max_value = 0xffff_ffff; self.max_value = 0xffff_ffff;
} }
if idx_num.contains(QueryPlanFlags::STEP) { if idx_num.contains(QueryPlanFlags::STEP) {
self.step = try!(args.get(i)); self.step = args.get(i)?;
if self.step < 1 { if self.step < 1 {
self.step = 1; self.step = 1;
} }
@ -263,9 +263,9 @@ impl VTabCursor for SeriesTabCursor {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use ffi; use crate::ffi;
use vtab::series; use crate::vtab::series;
use {Connection, NO_PARAMS}; use crate::{Connection, NO_PARAMS};
#[test] #[test]
fn test_series_module() { fn test_series_module() {