mirror of
https://github.com/isar/rusqlite.git
synced 2024-11-23 00:39:20 +08:00
Rename SqliteResult
-> Result
.
This commit is contained in:
parent
f0b6bf9152
commit
eb60bb3111
@ -1,7 +1,10 @@
|
|||||||
# Version UPCOMING (TBD)
|
# Version UPCOMING (TBD)
|
||||||
|
|
||||||
* Renamed `SqliteConnection` to `Connection`. The old name remains as a typealias.
|
* Removed `Sqlite` prefix on many types:
|
||||||
* Renamed `SqliteError` to `Error`. The old name remains as a typealias.
|
* `SqliteConnection` is now `Connection`
|
||||||
|
* `SqliteError` is now `Error`
|
||||||
|
* `SqliteResult` is now `Result`
|
||||||
|
The old, prefixed names are still exported should be considered deprecated.
|
||||||
* Adds a variety of `..._named` methods for executing queries using named placeholder parameters.
|
* Adds a variety of `..._named` methods for executing queries using named placeholder parameters.
|
||||||
* Adds `backup` feature that exposes SQLite's online backup API.
|
* Adds `backup` feature that exposes SQLite's online backup API.
|
||||||
* Adds `functions` feature that allows user-defined scalar functions to be added to
|
* Adds `functions` feature that allows user-defined scalar functions to be added to
|
||||||
|
@ -72,7 +72,7 @@ performing checks at runtime to ensure you do not try to retrieve the values of
|
|||||||
will panic if you do so. A specific example that will panic:
|
will panic if you do so. A specific example that will panic:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
fn bad_function_will_panic(conn: &Connection) -> SqliteResult<i64> {
|
fn bad_function_will_panic(conn: &Connection) -> Result<i64> {
|
||||||
let mut stmt = try!(conn.prepare("SELECT id FROM my_table"));
|
let mut stmt = try!(conn.prepare("SELECT id FROM my_table"));
|
||||||
let mut rows = try!(stmt.query(&[]));
|
let mut rows = try!(stmt.query(&[]));
|
||||||
|
|
||||||
|
@ -14,12 +14,12 @@
|
|||||||
//! documentation](https://www.sqlite.org/backup.html).
|
//! documentation](https://www.sqlite.org/backup.html).
|
||||||
//!
|
//!
|
||||||
//! ```rust,no_run
|
//! ```rust,no_run
|
||||||
//! # use rusqlite::{backup, Connection, SqliteResult};
|
//! # use rusqlite::{backup, Connection, Result};
|
||||||
//! # use std::path::Path;
|
//! # use std::path::Path;
|
||||||
//! # use std::time;
|
//! # use std::time;
|
||||||
//!
|
//!
|
||||||
//! fn backupDb<P: AsRef<Path>>(src: &Connection, dst: P, progress: fn(backup::Progress))
|
//! fn backupDb<P: AsRef<Path>>(src: &Connection, dst: P, progress: fn(backup::Progress))
|
||||||
//! -> SqliteResult<()> {
|
//! -> Result<()> {
|
||||||
//! let mut dst = try!(Connection::open(dst));
|
//! let mut dst = try!(Connection::open(dst));
|
||||||
//! let backup = try!(backup::Backup::new(src, &mut dst));
|
//! let backup = try!(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))
|
||||||
@ -36,7 +36,7 @@ use std::time::Duration;
|
|||||||
|
|
||||||
use ffi;
|
use ffi;
|
||||||
|
|
||||||
use {DatabaseName, Connection, Error, SqliteResult};
|
use {DatabaseName, Connection, Error, 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.
|
||||||
@ -55,7 +55,7 @@ impl Connection {
|
|||||||
name: DatabaseName,
|
name: DatabaseName,
|
||||||
dst_path: P,
|
dst_path: P,
|
||||||
progress: Option<fn(Progress)>)
|
progress: Option<fn(Progress)>)
|
||||||
-> SqliteResult<()> {
|
-> Result<()> {
|
||||||
use self::StepResult::{More, Done, Busy, Locked};
|
use self::StepResult::{More, Done, Busy, Locked};
|
||||||
let mut dst = try!(Connection::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 backup = try!(Backup::new_with_names(self, name, &mut dst, DatabaseName::Main));
|
||||||
@ -92,7 +92,7 @@ impl Connection {
|
|||||||
name: DatabaseName,
|
name: DatabaseName,
|
||||||
src_path: P,
|
src_path: P,
|
||||||
progress: Option<fn(Progress)>)
|
progress: Option<fn(Progress)>)
|
||||||
-> SqliteResult<()> {
|
-> Result<()> {
|
||||||
use self::StepResult::{More, Done, Busy, Locked};
|
use self::StepResult::{More, Done, Busy, Locked};
|
||||||
let src = try!(Connection::open(src_path));
|
let src = try!(Connection::open(src_path));
|
||||||
let restore = try!(Backup::new_with_names(&src, DatabaseName::Main, self, name));
|
let restore = try!(Backup::new_with_names(&src, DatabaseName::Main, self, name));
|
||||||
@ -172,7 +172,7 @@ impl<'a, 'b> Backup<'a, 'b> {
|
|||||||
/// `NULL`.
|
/// `NULL`.
|
||||||
pub fn new(from: &'a Connection,
|
pub fn new(from: &'a Connection,
|
||||||
to: &'b mut Connection)
|
to: &'b mut Connection)
|
||||||
-> SqliteResult<Backup<'a, 'b>> {
|
-> Result<Backup<'a, 'b>> {
|
||||||
Backup::new_with_names(from, DatabaseName::Main, to, DatabaseName::Main)
|
Backup::new_with_names(from, DatabaseName::Main, to, DatabaseName::Main)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -189,7 +189,7 @@ impl<'a, 'b> Backup<'a, 'b> {
|
|||||||
from_name: DatabaseName,
|
from_name: DatabaseName,
|
||||||
to: &'b mut Connection,
|
to: &'b mut Connection,
|
||||||
to_name: DatabaseName)
|
to_name: DatabaseName)
|
||||||
-> SqliteResult<Backup<'a, 'b>> {
|
-> Result<Backup<'a, 'b>> {
|
||||||
let to_name = try!(to_name.to_cstring());
|
let to_name = try!(to_name.to_cstring());
|
||||||
let from_name = try!(from_name.to_cstring());
|
let from_name = try!(from_name.to_cstring());
|
||||||
|
|
||||||
@ -235,7 +235,7 @@ impl<'a, 'b> Backup<'a, 'b> {
|
|||||||
/// an error code other than `DONE`, `OK`, `BUSY`, or `LOCKED`. `BUSY` and
|
/// an error code other than `DONE`, `OK`, `BUSY`, or `LOCKED`. `BUSY` and
|
||||||
/// `LOCKED` are transient errors and are therefore returned as possible
|
/// `LOCKED` are transient errors and are therefore returned as possible
|
||||||
/// `Ok` values.
|
/// `Ok` values.
|
||||||
pub fn step(&self, num_pages: c_int) -> SqliteResult<StepResult> {
|
pub fn step(&self, num_pages: c_int) -> Result<StepResult> {
|
||||||
use self::StepResult::{Done, More, Busy, Locked};
|
use self::StepResult::{Done, More, Busy, Locked};
|
||||||
|
|
||||||
let rc = unsafe { ffi::sqlite3_backup_step(self.b, num_pages) };
|
let rc = unsafe { ffi::sqlite3_backup_step(self.b, num_pages) };
|
||||||
@ -272,7 +272,7 @@ impl<'a, 'b> Backup<'a, 'b> {
|
|||||||
pages_per_step: c_int,
|
pages_per_step: c_int,
|
||||||
pause_between_pages: Duration,
|
pause_between_pages: Duration,
|
||||||
progress: Option<fn(Progress)>)
|
progress: Option<fn(Progress)>)
|
||||||
-> SqliteResult<()> {
|
-> Result<()> {
|
||||||
use self::StepResult::{Done, More, Busy, Locked};
|
use self::StepResult::{Done, More, Busy, Locked};
|
||||||
|
|
||||||
assert!(pages_per_step > 0, "pages_per_step must be positive");
|
assert!(pages_per_step > 0, "pages_per_step must be positive");
|
||||||
|
@ -12,11 +12,11 @@
|
|||||||
//! extern crate rusqlite;
|
//! extern crate rusqlite;
|
||||||
//! extern crate regex;
|
//! extern crate regex;
|
||||||
//!
|
//!
|
||||||
//! use rusqlite::{Connection, Error, SqliteResult};
|
//! use rusqlite::{Connection, Error, Result};
|
||||||
//! use std::collections::HashMap;
|
//! use std::collections::HashMap;
|
||||||
//! use regex::Regex;
|
//! use regex::Regex;
|
||||||
//!
|
//!
|
||||||
//! fn add_regexp_function(db: &Connection) -> SqliteResult<()> {
|
//! 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 = try!(ctx.get::<String>(0));
|
||||||
@ -65,7 +65,7 @@ pub use ffi::sqlite3_value_numeric_type;
|
|||||||
|
|
||||||
use types::Null;
|
use types::Null;
|
||||||
|
|
||||||
use {SqliteResult, Error, Connection, str_to_cstring, InnerConnection};
|
use {Result, Error, Connection, str_to_cstring, InnerConnection};
|
||||||
|
|
||||||
/// A trait for types that can be converted into the result of an SQL function.
|
/// A trait for types that can be converted into the result of an SQL function.
|
||||||
pub trait ToResult {
|
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.
|
/// A trait for types that can be created from a SQLite function parameter value.
|
||||||
pub trait FromValue: Sized {
|
pub trait FromValue: Sized {
|
||||||
unsafe fn parameter_value(v: *mut sqlite3_value) -> SqliteResult<Self>;
|
unsafe fn parameter_value(v: *mut sqlite3_value) -> Result<Self>;
|
||||||
|
|
||||||
/// FromValue types can implement this method and use sqlite3_value_type to check that
|
/// 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
|
/// 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(
|
macro_rules! raw_from_impl(
|
||||||
($t:ty, $f:ident, $c:expr) => (
|
($t:ty, $f:ident, $c:expr) => (
|
||||||
impl FromValue for $t {
|
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))
|
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);
|
raw_from_impl!(i64, sqlite3_value_int64, ffi::SQLITE_INTEGER);
|
||||||
|
|
||||||
impl FromValue for bool {
|
impl FromValue for bool {
|
||||||
unsafe fn parameter_value(v: *mut sqlite3_value) -> SqliteResult<bool> {
|
unsafe fn parameter_value(v: *mut sqlite3_value) -> Result<bool> {
|
||||||
match ffi::sqlite3_value_int(v) {
|
match ffi::sqlite3_value_int(v) {
|
||||||
0 => Ok(false),
|
0 => Ok(false),
|
||||||
_ => Ok(true),
|
_ => Ok(true),
|
||||||
@ -208,7 +208,7 @@ impl FromValue for bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl FromValue for c_double {
|
impl FromValue for c_double {
|
||||||
unsafe fn parameter_value(v: *mut sqlite3_value) -> SqliteResult<c_double> {
|
unsafe fn parameter_value(v: *mut sqlite3_value) -> Result<c_double> {
|
||||||
Ok(ffi::sqlite3_value_double(v))
|
Ok(ffi::sqlite3_value_double(v))
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -219,7 +219,7 @@ impl FromValue for c_double {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl FromValue for String {
|
impl FromValue for String {
|
||||||
unsafe fn parameter_value(v: *mut sqlite3_value) -> SqliteResult<String> {
|
unsafe fn parameter_value(v: *mut sqlite3_value) -> Result<String> {
|
||||||
let c_text = ffi::sqlite3_value_text(v);
|
let c_text = ffi::sqlite3_value_text(v);
|
||||||
if c_text.is_null() {
|
if c_text.is_null() {
|
||||||
Ok("".to_string())
|
Ok("".to_string())
|
||||||
@ -242,7 +242,7 @@ impl FromValue for String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl FromValue for Vec<u8> {
|
impl FromValue for Vec<u8> {
|
||||||
unsafe fn parameter_value(v: *mut sqlite3_value) -> SqliteResult<Vec<u8>> {
|
unsafe fn parameter_value(v: *mut sqlite3_value) -> Result<Vec<u8>> {
|
||||||
use std::slice::from_raw_parts;
|
use std::slice::from_raw_parts;
|
||||||
let c_blob = ffi::sqlite3_value_blob(v);
|
let c_blob = ffi::sqlite3_value_blob(v);
|
||||||
let len = ffi::sqlite3_value_bytes(v);
|
let len = ffi::sqlite3_value_bytes(v);
|
||||||
@ -260,7 +260,7 @@ impl FromValue for Vec<u8> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<T: FromValue> FromValue for Option<T> {
|
impl<T: FromValue> FromValue for Option<T> {
|
||||||
unsafe fn parameter_value(v: *mut sqlite3_value) -> SqliteResult<Option<T>> {
|
unsafe fn parameter_value(v: *mut sqlite3_value) -> Result<Option<T>> {
|
||||||
if sqlite3_value_type(v) == ffi::SQLITE_NULL {
|
if sqlite3_value_type(v) == ffi::SQLITE_NULL {
|
||||||
Ok(None)
|
Ok(None)
|
||||||
} else {
|
} else {
|
||||||
@ -296,7 +296,7 @@ impl<'a> Context<'a> {
|
|||||||
/// Will panic if `idx` is greater than or equal to `self.len()`.
|
/// 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`.
|
/// Will return Err if the underlying SQLite type cannot be converted to a `T`.
|
||||||
pub fn get<T: FromValue>(&self, idx: usize) -> SqliteResult<T> {
|
pub fn get<T: FromValue>(&self, idx: usize) -> Result<T> {
|
||||||
let arg = self.args[idx];
|
let arg = self.args[idx];
|
||||||
unsafe {
|
unsafe {
|
||||||
if T::parameter_has_valid_sqlite_type(arg) {
|
if T::parameter_has_valid_sqlite_type(arg) {
|
||||||
@ -355,9 +355,9 @@ impl Connection {
|
|||||||
/// # Example
|
/// # Example
|
||||||
///
|
///
|
||||||
/// ```rust
|
/// ```rust
|
||||||
/// # use rusqlite::{Connection, SqliteResult};
|
/// # use rusqlite::{Connection, Result};
|
||||||
/// # type c_double = f64;
|
/// # type c_double = f64;
|
||||||
/// fn scalar_function_example(db: Connection) -> SqliteResult<()> {
|
/// fn scalar_function_example(db: Connection) -> Result<()> {
|
||||||
/// try!(db.create_scalar_function("halve", 1, true, |ctx| {
|
/// try!(db.create_scalar_function("halve", 1, true, |ctx| {
|
||||||
/// let value = try!(ctx.get::<c_double>(0));
|
/// let value = try!(ctx.get::<c_double>(0));
|
||||||
/// Ok(value / 2f64)
|
/// Ok(value / 2f64)
|
||||||
@ -377,8 +377,8 @@ impl Connection {
|
|||||||
n_arg: c_int,
|
n_arg: c_int,
|
||||||
deterministic: bool,
|
deterministic: bool,
|
||||||
x_func: F)
|
x_func: F)
|
||||||
-> SqliteResult<()>
|
-> Result<()>
|
||||||
where F: FnMut(&Context) -> SqliteResult<T>,
|
where F: FnMut(&Context) -> Result<T>,
|
||||||
T: ToResult
|
T: ToResult
|
||||||
{
|
{
|
||||||
self.db.borrow_mut().create_scalar_function(fn_name, n_arg, deterministic, x_func)
|
self.db.borrow_mut().create_scalar_function(fn_name, n_arg, deterministic, x_func)
|
||||||
@ -392,7 +392,7 @@ impl Connection {
|
|||||||
/// # Failure
|
/// # Failure
|
||||||
///
|
///
|
||||||
/// Will return Err if the function could not be removed.
|
/// 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)
|
self.db.borrow_mut().remove_function(fn_name, n_arg)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -403,14 +403,14 @@ impl InnerConnection {
|
|||||||
n_arg: c_int,
|
n_arg: c_int,
|
||||||
deterministic: bool,
|
deterministic: bool,
|
||||||
x_func: F)
|
x_func: F)
|
||||||
-> SqliteResult<()>
|
-> Result<()>
|
||||||
where F: FnMut(&Context) -> SqliteResult<T>,
|
where F: FnMut(&Context) -> Result<T>,
|
||||||
T: ToResult
|
T: ToResult
|
||||||
{
|
{
|
||||||
extern "C" fn call_boxed_closure<F, T>(ctx: *mut sqlite3_context,
|
extern "C" fn call_boxed_closure<F, T>(ctx: *mut sqlite3_context,
|
||||||
argc: c_int,
|
argc: c_int,
|
||||||
argv: *mut *mut sqlite3_value)
|
argv: *mut *mut sqlite3_value)
|
||||||
where F: FnMut(&Context) -> SqliteResult<T>,
|
where F: FnMut(&Context) -> Result<T>,
|
||||||
T: ToResult
|
T: ToResult
|
||||||
{
|
{
|
||||||
unsafe {
|
unsafe {
|
||||||
@ -452,7 +452,7 @@ impl InnerConnection {
|
|||||||
self.decode_result(r)
|
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 c_name = try!(str_to_cstring(fn_name));
|
||||||
let r = unsafe {
|
let r = unsafe {
|
||||||
ffi::sqlite3_create_function_v2(self.db(),
|
ffi::sqlite3_create_function_v2(self.db(),
|
||||||
@ -477,11 +477,11 @@ mod test {
|
|||||||
use libc::c_double;
|
use libc::c_double;
|
||||||
use self::regex::Regex;
|
use self::regex::Regex;
|
||||||
|
|
||||||
use {Connection, Error, SqliteResult};
|
use {Connection, Error, Result};
|
||||||
use ffi;
|
use ffi;
|
||||||
use functions::Context;
|
use functions::Context;
|
||||||
|
|
||||||
fn half(ctx: &Context) -> SqliteResult<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 = try!(ctx.get::<c_double>(0));
|
||||||
Ok(value / 2f64)
|
Ok(value / 2f64)
|
||||||
@ -511,7 +511,7 @@ mod test {
|
|||||||
// This implementation of a regexp scalar function uses SQLite's auxilliary data
|
// 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
|
// (https://www.sqlite.org/c3ref/get_auxdata.html) to avoid recompiling the regular
|
||||||
// expression multiple times within one query.
|
// expression multiple times within one query.
|
||||||
fn regexp_with_auxilliary(ctx: &Context) -> SqliteResult<bool> {
|
fn regexp_with_auxilliary(ctx: &Context) -> Result<bool> {
|
||||||
assert!(ctx.len() == 2, "called with unexpected number of arguments");
|
assert!(ctx.len() == 2, "called with unexpected number of arguments");
|
||||||
|
|
||||||
let saved_re: Option<&Regex> = unsafe { ctx.get_aux(0) };
|
let saved_re: Option<&Regex> = unsafe { ctx.get_aux(0) };
|
||||||
|
170
src/lib.rs
170
src/lib.rs
@ -68,6 +68,7 @@ use std::error;
|
|||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
use std::cell::{RefCell, Cell};
|
use std::cell::{RefCell, Cell};
|
||||||
use std::ffi::{CStr, CString};
|
use std::ffi::{CStr, CString};
|
||||||
|
use std::result;
|
||||||
use std::str;
|
use std::str;
|
||||||
use libc::{c_int, c_void, c_char};
|
use libc::{c_int, c_void, c_char};
|
||||||
|
|
||||||
@ -88,8 +89,11 @@ mod named_params;
|
|||||||
#[cfg(feature = "backup")]pub mod backup;
|
#[cfg(feature = "backup")]pub mod backup;
|
||||||
#[cfg(feature = "functions")] pub mod functions;
|
#[cfg(feature = "functions")] pub mod functions;
|
||||||
|
|
||||||
|
/// Old name for `Result`. `SqliteResult` is deprecated.
|
||||||
|
pub type SqliteResult<T> = Result<T>;
|
||||||
|
|
||||||
/// A typedef of the result returned by many methods.
|
/// A typedef of the result returned by many methods.
|
||||||
pub type SqliteResult<T> = Result<T, Error>;
|
pub type Result<T> = result::Result<T, Error>;
|
||||||
|
|
||||||
unsafe fn errmsg_to_string(errmsg: *const c_char) -> String {
|
unsafe fn errmsg_to_string(errmsg: *const c_char) -> String {
|
||||||
let c_slice = CStr::from_ptr(errmsg).to_bytes();
|
let c_slice = CStr::from_ptr(errmsg).to_bytes();
|
||||||
@ -138,7 +142,7 @@ impl Error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn str_to_cstring(s: &str) -> SqliteResult<CString> {
|
fn str_to_cstring(s: &str) -> Result<CString> {
|
||||||
CString::new(s).map_err(|_| {
|
CString::new(s).map_err(|_| {
|
||||||
Error {
|
Error {
|
||||||
code: ffi::SQLITE_MISUSE,
|
code: ffi::SQLITE_MISUSE,
|
||||||
@ -147,7 +151,7 @@ fn str_to_cstring(s: &str) -> SqliteResult<CString> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn path_to_cstring(p: &Path) -> SqliteResult<CString> {
|
fn path_to_cstring(p: &Path) -> Result<CString> {
|
||||||
let s = try!(p.to_str().ok_or(Error {
|
let s = try!(p.to_str().ok_or(Error {
|
||||||
code: ffi::SQLITE_MISUSE,
|
code: ffi::SQLITE_MISUSE,
|
||||||
message: format!("Could not convert path {} to UTF-8 string",
|
message: format!("Could not convert path {} to UTF-8 string",
|
||||||
@ -172,7 +176,7 @@ pub enum DatabaseName<'a> {
|
|||||||
// impl to avoid dead code warnings.
|
// impl to avoid dead code warnings.
|
||||||
#[cfg(feature = "backup")]
|
#[cfg(feature = "backup")]
|
||||||
impl<'a> DatabaseName<'a> {
|
impl<'a> DatabaseName<'a> {
|
||||||
fn to_cstring(self) -> SqliteResult<CString> {
|
fn to_cstring(self) -> Result<CString> {
|
||||||
use self::DatabaseName::{Main, Temp, Attached};
|
use self::DatabaseName::{Main, Temp, Attached};
|
||||||
match self {
|
match self {
|
||||||
Main => str_to_cstring("main"),
|
Main => str_to_cstring("main"),
|
||||||
@ -203,7 +207,7 @@ impl Connection {
|
|||||||
///
|
///
|
||||||
/// Will return `Err` if `path` cannot be converted to a C-compatible string or if the
|
/// Will return `Err` if `path` cannot be converted to a C-compatible string or if the
|
||||||
/// underlying SQLite open call fails.
|
/// underlying SQLite open call fails.
|
||||||
pub fn open<P: AsRef<Path>>(path: P) -> SqliteResult<Connection> {
|
pub fn open<P: AsRef<Path>>(path: P) -> Result<Connection> {
|
||||||
let flags = Default::default();
|
let flags = Default::default();
|
||||||
Connection::open_with_flags(path, flags)
|
Connection::open_with_flags(path, flags)
|
||||||
}
|
}
|
||||||
@ -213,7 +217,7 @@ impl Connection {
|
|||||||
/// # Failure
|
/// # Failure
|
||||||
///
|
///
|
||||||
/// 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() -> SqliteResult<Connection> {
|
pub fn open_in_memory() -> Result<Connection> {
|
||||||
let flags = Default::default();
|
let flags = Default::default();
|
||||||
Connection::open_in_memory_with_flags(flags)
|
Connection::open_in_memory_with_flags(flags)
|
||||||
}
|
}
|
||||||
@ -229,7 +233,7 @@ impl Connection {
|
|||||||
/// underlying SQLite open call fails.
|
/// underlying SQLite open call fails.
|
||||||
pub fn open_with_flags<P: AsRef<Path>>(path: P,
|
pub fn open_with_flags<P: AsRef<Path>>(path: P,
|
||||||
flags: SqliteOpenFlags)
|
flags: SqliteOpenFlags)
|
||||||
-> SqliteResult<Connection> {
|
-> Result<Connection> {
|
||||||
let c_path = try!(path_to_cstring(path.as_ref()));
|
let c_path = try!(path_to_cstring(path.as_ref()));
|
||||||
InnerConnection::open_with_flags(&c_path, flags).map(|db| {
|
InnerConnection::open_with_flags(&c_path, flags).map(|db| {
|
||||||
Connection {
|
Connection {
|
||||||
@ -247,7 +251,7 @@ impl Connection {
|
|||||||
/// # Failure
|
/// # Failure
|
||||||
///
|
///
|
||||||
/// 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: SqliteOpenFlags) -> SqliteResult<Connection> {
|
pub fn open_in_memory_with_flags(flags: SqliteOpenFlags) -> Result<Connection> {
|
||||||
let c_memory = try!(str_to_cstring(":memory:"));
|
let c_memory = try!(str_to_cstring(":memory:"));
|
||||||
InnerConnection::open_with_flags(&c_memory, flags).map(|db| {
|
InnerConnection::open_with_flags(&c_memory, flags).map(|db| {
|
||||||
Connection {
|
Connection {
|
||||||
@ -265,10 +269,10 @@ impl Connection {
|
|||||||
/// ## Example
|
/// ## Example
|
||||||
///
|
///
|
||||||
/// ```rust,no_run
|
/// ```rust,no_run
|
||||||
/// # use rusqlite::{Connection, SqliteResult};
|
/// # use rusqlite::{Connection, Result};
|
||||||
/// # fn do_queries_part_1(conn: &Connection) -> SqliteResult<()> { Ok(()) }
|
/// # fn do_queries_part_1(conn: &Connection) -> Result<()> { Ok(()) }
|
||||||
/// # fn do_queries_part_2(conn: &Connection) -> SqliteResult<()> { Ok(()) }
|
/// # fn do_queries_part_2(conn: &Connection) -> Result<()> { Ok(()) }
|
||||||
/// fn perform_queries(conn: &Connection) -> SqliteResult<()> {
|
/// fn perform_queries(conn: &Connection) -> Result<()> {
|
||||||
/// let tx = try!(conn.transaction());
|
/// let tx = try!(conn.transaction());
|
||||||
///
|
///
|
||||||
/// try!(do_queries_part_1(conn)); // tx causes rollback if this fails
|
/// try!(do_queries_part_1(conn)); // tx causes rollback if this fails
|
||||||
@ -281,7 +285,7 @@ impl Connection {
|
|||||||
/// # Failure
|
/// # Failure
|
||||||
///
|
///
|
||||||
/// Will return `Err` if the underlying SQLite call fails.
|
/// Will return `Err` if the underlying SQLite call fails.
|
||||||
pub fn transaction<'a>(&'a self) -> SqliteResult<SqliteTransaction<'a>> {
|
pub fn transaction<'a>(&'a self) -> Result<SqliteTransaction<'a>> {
|
||||||
SqliteTransaction::new(self, SqliteTransactionDeferred)
|
SqliteTransaction::new(self, SqliteTransactionDeferred)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -294,7 +298,7 @@ impl Connection {
|
|||||||
/// Will return `Err` if the underlying SQLite call fails.
|
/// Will return `Err` if the underlying SQLite call fails.
|
||||||
pub fn transaction_with_behavior<'a>(&'a self,
|
pub fn transaction_with_behavior<'a>(&'a self,
|
||||||
behavior: SqliteTransactionBehavior)
|
behavior: SqliteTransactionBehavior)
|
||||||
-> SqliteResult<SqliteTransaction<'a>> {
|
-> Result<SqliteTransaction<'a>> {
|
||||||
SqliteTransaction::new(self, behavior)
|
SqliteTransaction::new(self, behavior)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -305,8 +309,8 @@ impl Connection {
|
|||||||
/// ## Example
|
/// ## Example
|
||||||
///
|
///
|
||||||
/// ```rust,no_run
|
/// ```rust,no_run
|
||||||
/// # use rusqlite::{Connection, SqliteResult};
|
/// # use rusqlite::{Connection, Result};
|
||||||
/// fn create_tables(conn: &Connection) -> SqliteResult<()> {
|
/// fn create_tables(conn: &Connection) -> Result<()> {
|
||||||
/// conn.execute_batch("BEGIN;
|
/// conn.execute_batch("BEGIN;
|
||||||
/// CREATE TABLE foo(x INTEGER);
|
/// CREATE TABLE foo(x INTEGER);
|
||||||
/// CREATE TABLE bar(y TEXT);
|
/// CREATE TABLE bar(y TEXT);
|
||||||
@ -318,7 +322,7 @@ impl Connection {
|
|||||||
///
|
///
|
||||||
/// Will return `Err` if `sql` cannot be converted to a C-compatible string or if the
|
/// Will return `Err` if `sql` cannot be converted to a C-compatible string or if the
|
||||||
/// underlying SQLite call fails.
|
/// underlying SQLite call fails.
|
||||||
pub fn execute_batch(&self, sql: &str) -> SqliteResult<()> {
|
pub fn execute_batch(&self, sql: &str) -> Result<()> {
|
||||||
self.db.borrow_mut().execute_batch(sql)
|
self.db.borrow_mut().execute_batch(sql)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -343,7 +347,7 @@ impl Connection {
|
|||||||
///
|
///
|
||||||
/// Will return `Err` if `sql` cannot be converted to a C-compatible string or if the
|
/// Will return `Err` if `sql` cannot be converted to a C-compatible string or if the
|
||||||
/// underlying SQLite call fails.
|
/// underlying SQLite call fails.
|
||||||
pub fn execute(&self, sql: &str, params: &[&ToSql]) -> SqliteResult<c_int> {
|
pub fn execute(&self, sql: &str, params: &[&ToSql]) -> Result<c_int> {
|
||||||
self.prepare(sql).and_then(|mut stmt| stmt.execute(params))
|
self.prepare(sql).and_then(|mut stmt| stmt.execute(params))
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -360,8 +364,8 @@ impl Connection {
|
|||||||
/// ## Example
|
/// ## Example
|
||||||
///
|
///
|
||||||
/// ```rust,no_run
|
/// ```rust,no_run
|
||||||
/// # use rusqlite::{SqliteResult,Connection};
|
/// # use rusqlite::{Result,Connection};
|
||||||
/// fn preferred_locale(conn: &Connection) -> SqliteResult<String> {
|
/// fn preferred_locale(conn: &Connection) -> Result<String> {
|
||||||
/// conn.query_row("SELECT value FROM preferences WHERE name='locale'", &[], |row| {
|
/// conn.query_row("SELECT value FROM preferences WHERE name='locale'", &[], |row| {
|
||||||
/// row.get(0)
|
/// row.get(0)
|
||||||
/// })
|
/// })
|
||||||
@ -374,7 +378,7 @@ impl Connection {
|
|||||||
///
|
///
|
||||||
/// Will return `Err` if `sql` cannot be converted to a C-compatible string or if the
|
/// Will return `Err` if `sql` cannot be converted to a C-compatible string or if the
|
||||||
/// underlying SQLite call fails.
|
/// underlying SQLite call fails.
|
||||||
pub fn query_row<T, F>(&self, sql: &str, params: &[&ToSql], f: F) -> SqliteResult<T>
|
pub fn query_row<T, F>(&self, sql: &str, params: &[&ToSql], f: F) -> Result<T>
|
||||||
where F: FnOnce(SqliteRow) -> T
|
where F: FnOnce(SqliteRow) -> T
|
||||||
{
|
{
|
||||||
let mut stmt = try!(self.prepare(sql));
|
let mut stmt = try!(self.prepare(sql));
|
||||||
@ -390,8 +394,8 @@ impl Connection {
|
|||||||
/// ## Example
|
/// ## Example
|
||||||
///
|
///
|
||||||
/// ```rust,no_run
|
/// ```rust,no_run
|
||||||
/// # use rusqlite::{SqliteResult,Connection};
|
/// # use rusqlite::{Result,Connection};
|
||||||
/// fn preferred_locale(conn: &Connection) -> SqliteResult<String> {
|
/// fn preferred_locale(conn: &Connection) -> Result<String> {
|
||||||
/// conn.query_row_and_then("SELECT value FROM preferences WHERE name='locale'", &[], |row| {
|
/// conn.query_row_and_then("SELECT value FROM preferences WHERE name='locale'", &[], |row| {
|
||||||
/// row.get_checked(0)
|
/// row.get_checked(0)
|
||||||
/// })
|
/// })
|
||||||
@ -404,8 +408,8 @@ impl Connection {
|
|||||||
///
|
///
|
||||||
/// Will return `Err` if `sql` cannot be converted to a C-compatible string or if the
|
/// Will return `Err` if `sql` cannot be converted to a C-compatible string or if the
|
||||||
/// underlying SQLite call fails.
|
/// underlying SQLite call fails.
|
||||||
pub fn query_row_and_then<T, E, F>(&self, sql: &str, params: &[&ToSql], f: F) -> Result<T, E>
|
pub fn query_row_and_then<T, E, F>(&self, sql: &str, params: &[&ToSql], f: F) -> result::Result<T, E>
|
||||||
where F: FnOnce(SqliteRow) -> Result<T, E>,
|
where F: FnOnce(SqliteRow) -> result::Result<T, E>,
|
||||||
E: convert::From<Error>
|
E: convert::From<Error>
|
||||||
{
|
{
|
||||||
let mut stmt = try!(self.prepare(sql));
|
let mut stmt = try!(self.prepare(sql));
|
||||||
@ -419,8 +423,8 @@ impl Connection {
|
|||||||
/// ## Example
|
/// ## Example
|
||||||
///
|
///
|
||||||
/// ```rust,no_run
|
/// ```rust,no_run
|
||||||
/// # use rusqlite::{SqliteResult,Connection};
|
/// # use rusqlite::{Result,Connection};
|
||||||
/// fn preferred_locale(conn: &Connection) -> SqliteResult<String> {
|
/// fn preferred_locale(conn: &Connection) -> Result<String> {
|
||||||
/// conn.query_row_safe("SELECT value FROM preferences WHERE name='locale'", &[], |row| {
|
/// conn.query_row_safe("SELECT value FROM preferences WHERE name='locale'", &[], |row| {
|
||||||
/// row.get(0)
|
/// row.get(0)
|
||||||
/// })
|
/// })
|
||||||
@ -433,7 +437,7 @@ impl Connection {
|
|||||||
///
|
///
|
||||||
/// This method should be considered deprecated. Use `query_row` instead, which now
|
/// This method should be considered deprecated. Use `query_row` instead, which now
|
||||||
/// does exactly the same thing.
|
/// does exactly the same thing.
|
||||||
pub fn query_row_safe<T, F>(&self, sql: &str, params: &[&ToSql], f: F) -> SqliteResult<T>
|
pub fn query_row_safe<T, F>(&self, sql: &str, params: &[&ToSql], f: F) -> Result<T>
|
||||||
where F: FnOnce(SqliteRow) -> T
|
where F: FnOnce(SqliteRow) -> T
|
||||||
{
|
{
|
||||||
self.query_row(sql, params, f)
|
self.query_row(sql, params, f)
|
||||||
@ -444,8 +448,8 @@ impl Connection {
|
|||||||
/// ## Example
|
/// ## Example
|
||||||
///
|
///
|
||||||
/// ```rust,no_run
|
/// ```rust,no_run
|
||||||
/// # use rusqlite::{Connection, SqliteResult};
|
/// # use rusqlite::{Connection, Result};
|
||||||
/// fn insert_new_people(conn: &Connection) -> SqliteResult<()> {
|
/// fn insert_new_people(conn: &Connection) -> Result<()> {
|
||||||
/// let mut stmt = try!(conn.prepare("INSERT INTO People (name) VALUES (?)"));
|
/// let mut stmt = try!(conn.prepare("INSERT INTO People (name) VALUES (?)"));
|
||||||
/// try!(stmt.execute(&[&"Joe Smith"]));
|
/// try!(stmt.execute(&[&"Joe Smith"]));
|
||||||
/// try!(stmt.execute(&[&"Bob Jones"]));
|
/// try!(stmt.execute(&[&"Bob Jones"]));
|
||||||
@ -457,7 +461,7 @@ impl Connection {
|
|||||||
///
|
///
|
||||||
/// Will return `Err` if `sql` cannot be converted to a C-compatible string or if the
|
/// Will return `Err` if `sql` cannot be converted to a C-compatible string or if the
|
||||||
/// underlying SQLite call fails.
|
/// underlying SQLite call fails.
|
||||||
pub fn prepare<'a>(&'a self, sql: &str) -> SqliteResult<SqliteStatement<'a>> {
|
pub fn prepare<'a>(&'a self, sql: &str) -> Result<SqliteStatement<'a>> {
|
||||||
self.db.borrow_mut().prepare(self, sql)
|
self.db.borrow_mut().prepare(self, sql)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -469,7 +473,7 @@ impl Connection {
|
|||||||
/// # Failure
|
/// # Failure
|
||||||
///
|
///
|
||||||
/// Will return `Err` if the underlying SQLite call fails.
|
/// Will return `Err` if the underlying SQLite call fails.
|
||||||
pub fn close(self) -> SqliteResult<()> {
|
pub fn close(self) -> Result<()> {
|
||||||
let mut db = self.db.borrow_mut();
|
let mut db = self.db.borrow_mut();
|
||||||
db.close()
|
db.close()
|
||||||
}
|
}
|
||||||
@ -480,9 +484,9 @@ impl Connection {
|
|||||||
/// ## Example
|
/// ## Example
|
||||||
///
|
///
|
||||||
/// ```rust,no_run
|
/// ```rust,no_run
|
||||||
/// # use rusqlite::{Connection, SqliteResult};
|
/// # use rusqlite::{Connection, Result};
|
||||||
/// # use std::path::{Path};
|
/// # use std::path::{Path};
|
||||||
/// fn load_my_extension(conn: &Connection) -> SqliteResult<()> {
|
/// fn load_my_extension(conn: &Connection) -> Result<()> {
|
||||||
/// try!(conn.load_extension_enable());
|
/// try!(conn.load_extension_enable());
|
||||||
/// try!(conn.load_extension(Path::new("my_sqlite_extension"), None));
|
/// try!(conn.load_extension(Path::new("my_sqlite_extension"), None));
|
||||||
/// conn.load_extension_disable()
|
/// conn.load_extension_disable()
|
||||||
@ -493,7 +497,7 @@ impl Connection {
|
|||||||
///
|
///
|
||||||
/// Will return `Err` if the underlying SQLite call fails.
|
/// Will return `Err` if the underlying SQLite call fails.
|
||||||
#[cfg(feature = "load_extension")]
|
#[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)
|
self.db.borrow_mut().enable_load_extension(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -505,7 +509,7 @@ impl Connection {
|
|||||||
///
|
///
|
||||||
/// Will return `Err` if the underlying SQLite call fails.
|
/// Will return `Err` if the underlying SQLite call fails.
|
||||||
#[cfg(feature = "load_extension")]
|
#[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)
|
self.db.borrow_mut().enable_load_extension(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -519,9 +523,9 @@ impl Connection {
|
|||||||
/// ## Example
|
/// ## Example
|
||||||
///
|
///
|
||||||
/// ```rust,no_run
|
/// ```rust,no_run
|
||||||
/// # use rusqlite::{Connection, SqliteResult, SqliteLoadExtensionGuard};
|
/// # use rusqlite::{Connection, Result, SqliteLoadExtensionGuard};
|
||||||
/// # use std::path::{Path};
|
/// # use std::path::{Path};
|
||||||
/// fn load_my_extension(conn: &Connection) -> SqliteResult<()> {
|
/// fn load_my_extension(conn: &Connection) -> Result<()> {
|
||||||
/// let _guard = try!(SqliteLoadExtensionGuard::new(conn));
|
/// let _guard = try!(SqliteLoadExtensionGuard::new(conn));
|
||||||
///
|
///
|
||||||
/// conn.load_extension("my_sqlite_extension", None)
|
/// conn.load_extension("my_sqlite_extension", None)
|
||||||
@ -535,11 +539,11 @@ impl Connection {
|
|||||||
pub fn load_extension<P: AsRef<Path>>(&self,
|
pub fn load_extension<P: AsRef<Path>>(&self,
|
||||||
dylib_path: P,
|
dylib_path: P,
|
||||||
entry_point: Option<&str>)
|
entry_point: Option<&str>)
|
||||||
-> SqliteResult<()> {
|
-> Result<()> {
|
||||||
self.db.borrow_mut().load_extension(dylib_path.as_ref(), entry_point)
|
self.db.borrow_mut().load_extension(dylib_path.as_ref(), entry_point)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn decode_result(&self, code: c_int) -> SqliteResult<()> {
|
fn decode_result(&self, code: c_int) -> Result<()> {
|
||||||
self.db.borrow_mut().decode_result(code)
|
self.db.borrow_mut().decode_result(code)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -586,7 +590,7 @@ impl Default for SqliteOpenFlags {
|
|||||||
impl InnerConnection {
|
impl InnerConnection {
|
||||||
fn open_with_flags(c_path: &CString,
|
fn open_with_flags(c_path: &CString,
|
||||||
flags: SqliteOpenFlags)
|
flags: SqliteOpenFlags)
|
||||||
-> SqliteResult<InnerConnection> {
|
-> Result<InnerConnection> {
|
||||||
unsafe {
|
unsafe {
|
||||||
let mut db: *mut ffi::sqlite3 = mem::uninitialized();
|
let mut db: *mut ffi::sqlite3 = mem::uninitialized();
|
||||||
let r = ffi::sqlite3_open_v2(c_path.as_ptr(), &mut db, flags.bits(), ptr::null());
|
let r = ffi::sqlite3_open_v2(c_path.as_ptr(), &mut db, flags.bits(), ptr::null());
|
||||||
@ -618,7 +622,7 @@ impl InnerConnection {
|
|||||||
self.db
|
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 {
|
if code == ffi::SQLITE_OK {
|
||||||
Ok(())
|
Ok(())
|
||||||
} else {
|
} else {
|
||||||
@ -629,7 +633,7 @@ impl InnerConnection {
|
|||||||
unsafe fn decode_result_with_errmsg(&self,
|
unsafe fn decode_result_with_errmsg(&self,
|
||||||
code: c_int,
|
code: c_int,
|
||||||
errmsg: *mut c_char)
|
errmsg: *mut c_char)
|
||||||
-> SqliteResult<()> {
|
-> Result<()> {
|
||||||
if code == ffi::SQLITE_OK {
|
if code == ffi::SQLITE_OK {
|
||||||
Ok(())
|
Ok(())
|
||||||
} else {
|
} else {
|
||||||
@ -642,7 +646,7 @@ impl InnerConnection {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn close(&mut self) -> SqliteResult<()> {
|
fn close(&mut self) -> Result<()> {
|
||||||
unsafe {
|
unsafe {
|
||||||
let r = ffi::sqlite3_close(self.db());
|
let r = ffi::sqlite3_close(self.db());
|
||||||
self.db = ptr::null_mut();
|
self.db = ptr::null_mut();
|
||||||
@ -650,7 +654,7 @@ impl InnerConnection {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn execute_batch(&mut self, sql: &str) -> SqliteResult<()> {
|
fn execute_batch(&mut self, sql: &str) -> Result<()> {
|
||||||
let c_sql = try!(str_to_cstring(sql));
|
let c_sql = try!(str_to_cstring(sql));
|
||||||
unsafe {
|
unsafe {
|
||||||
let mut errmsg: *mut c_char = mem::uninitialized();
|
let mut errmsg: *mut c_char = mem::uninitialized();
|
||||||
@ -664,13 +668,13 @@ impl InnerConnection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "load_extension")]
|
#[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) };
|
let r = unsafe { ffi::sqlite3_enable_load_extension(self.db, onoff) };
|
||||||
self.decode_result(r)
|
self.decode_result(r)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "load_extension")]
|
#[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));
|
let dylib_str = try!(path_to_cstring(dylib_path));
|
||||||
unsafe {
|
unsafe {
|
||||||
let mut errmsg: *mut c_char = mem::uninitialized();
|
let mut errmsg: *mut c_char = mem::uninitialized();
|
||||||
@ -694,7 +698,7 @@ impl InnerConnection {
|
|||||||
fn prepare<'a>(&mut self,
|
fn prepare<'a>(&mut self,
|
||||||
conn: &'a Connection,
|
conn: &'a Connection,
|
||||||
sql: &str)
|
sql: &str)
|
||||||
-> SqliteResult<SqliteStatement<'a>> {
|
-> Result<SqliteStatement<'a>> {
|
||||||
if sql.len() >= ::std::i32::MAX as usize {
|
if sql.len() >= ::std::i32::MAX as usize {
|
||||||
return Err(Error {
|
return Err(Error {
|
||||||
code: ffi::SQLITE_TOOBIG,
|
code: ffi::SQLITE_TOOBIG,
|
||||||
@ -764,8 +768,8 @@ impl<'conn> SqliteStatement<'conn> {
|
|||||||
/// ## Example
|
/// ## Example
|
||||||
///
|
///
|
||||||
/// ```rust,no_run
|
/// ```rust,no_run
|
||||||
/// # use rusqlite::{Connection, SqliteResult};
|
/// # use rusqlite::{Connection, Result};
|
||||||
/// fn update_rows(conn: &Connection) -> SqliteResult<()> {
|
/// fn update_rows(conn: &Connection) -> Result<()> {
|
||||||
/// let mut stmt = try!(conn.prepare("UPDATE foo SET bar = 'baz' WHERE qux = ?"));
|
/// let mut stmt = try!(conn.prepare("UPDATE foo SET bar = 'baz' WHERE qux = ?"));
|
||||||
///
|
///
|
||||||
/// try!(stmt.execute(&[&1i32]));
|
/// try!(stmt.execute(&[&1i32]));
|
||||||
@ -779,14 +783,14 @@ impl<'conn> SqliteStatement<'conn> {
|
|||||||
///
|
///
|
||||||
/// Will return `Err` if binding parameters fails, the executed statement returns rows (in
|
/// 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.
|
/// which case `query` should be used instead), or the underling SQLite call fails.
|
||||||
pub fn execute(&mut self, params: &[&ToSql]) -> SqliteResult<c_int> {
|
pub fn execute(&mut self, params: &[&ToSql]) -> Result<c_int> {
|
||||||
unsafe {
|
unsafe {
|
||||||
try!(self.bind_parameters(params));
|
try!(self.bind_parameters(params));
|
||||||
self.execute_()
|
self.execute_()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
unsafe fn execute_(&mut self) -> SqliteResult<c_int> {
|
unsafe fn execute_(&mut self) -> Result<c_int> {
|
||||||
let r = ffi::sqlite3_step(self.stmt);
|
let r = ffi::sqlite3_step(self.stmt);
|
||||||
ffi::sqlite3_reset(self.stmt);
|
ffi::sqlite3_reset(self.stmt);
|
||||||
match r {
|
match r {
|
||||||
@ -816,8 +820,8 @@ impl<'conn> SqliteStatement<'conn> {
|
|||||||
/// ## Example
|
/// ## Example
|
||||||
///
|
///
|
||||||
/// ```rust,no_run
|
/// ```rust,no_run
|
||||||
/// # use rusqlite::{Connection, SqliteResult};
|
/// # use rusqlite::{Connection, Result};
|
||||||
/// fn get_names(conn: &Connection) -> SqliteResult<Vec<String>> {
|
/// fn get_names(conn: &Connection) -> Result<Vec<String>> {
|
||||||
/// let mut stmt = try!(conn.prepare("SELECT name FROM people"));
|
/// let mut stmt = try!(conn.prepare("SELECT name FROM people"));
|
||||||
/// let mut rows = try!(stmt.query(&[]));
|
/// let mut rows = try!(stmt.query(&[]));
|
||||||
///
|
///
|
||||||
@ -834,7 +838,7 @@ impl<'conn> SqliteStatement<'conn> {
|
|||||||
/// # Failure
|
/// # Failure
|
||||||
///
|
///
|
||||||
/// Will return `Err` if binding parameters fails.
|
/// Will return `Err` if binding parameters fails.
|
||||||
pub fn query<'a>(&'a mut self, params: &[&ToSql]) -> SqliteResult<SqliteRows<'a>> {
|
pub fn query<'a>(&'a mut self, params: &[&ToSql]) -> Result<SqliteRows<'a>> {
|
||||||
self.reset_if_needed();
|
self.reset_if_needed();
|
||||||
|
|
||||||
unsafe {
|
unsafe {
|
||||||
@ -857,7 +861,7 @@ impl<'conn> SqliteStatement<'conn> {
|
|||||||
pub fn query_map<'a, T, F>(&'a mut self,
|
pub fn query_map<'a, T, F>(&'a mut self,
|
||||||
params: &[&ToSql],
|
params: &[&ToSql],
|
||||||
f: F)
|
f: F)
|
||||||
-> SqliteResult<MappedRows<'a, F>>
|
-> Result<MappedRows<'a, F>>
|
||||||
where F: FnMut(&SqliteRow) -> T
|
where F: FnMut(&SqliteRow) -> T
|
||||||
{
|
{
|
||||||
let row_iter = try!(self.query(params));
|
let row_iter = try!(self.query(params));
|
||||||
@ -881,9 +885,9 @@ impl<'conn> SqliteStatement<'conn> {
|
|||||||
pub fn query_and_then<'a, T, E, F>(&'a mut self,
|
pub fn query_and_then<'a, T, E, F>(&'a mut self,
|
||||||
params: &[&ToSql],
|
params: &[&ToSql],
|
||||||
f: F)
|
f: F)
|
||||||
-> SqliteResult<AndThenRows<'a, F>>
|
-> Result<AndThenRows<'a, F>>
|
||||||
where E: convert::From<Error>,
|
where E: convert::From<Error>,
|
||||||
F: FnMut(&SqliteRow) -> Result<T, E>
|
F: FnMut(&SqliteRow) -> result::Result<T, E>
|
||||||
{
|
{
|
||||||
let row_iter = try!(self.query(params));
|
let row_iter = try!(self.query(params));
|
||||||
|
|
||||||
@ -901,11 +905,11 @@ impl<'conn> SqliteStatement<'conn> {
|
|||||||
/// # Failure
|
/// # Failure
|
||||||
///
|
///
|
||||||
/// Will return `Err` if the underlying SQLite call fails.
|
/// Will return `Err` if the underlying SQLite call fails.
|
||||||
pub fn finalize(mut self) -> SqliteResult<()> {
|
pub fn finalize(mut self) -> Result<()> {
|
||||||
self.finalize_()
|
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),
|
assert!(params.len() as c_int == ffi::sqlite3_bind_parameter_count(self.stmt),
|
||||||
"incorrect number of parameters to query(): expected {}, got {}",
|
"incorrect number of parameters to query(): expected {}, got {}",
|
||||||
ffi::sqlite3_bind_parameter_count(self.stmt),
|
ffi::sqlite3_bind_parameter_count(self.stmt),
|
||||||
@ -927,7 +931,7 @@ impl<'conn> SqliteStatement<'conn> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn finalize_(&mut self) -> SqliteResult<()> {
|
fn finalize_(&mut self) -> Result<()> {
|
||||||
let r = unsafe { ffi::sqlite3_finalize(self.stmt) };
|
let r = unsafe { ffi::sqlite3_finalize(self.stmt) };
|
||||||
self.stmt = ptr::null_mut();
|
self.stmt = ptr::null_mut();
|
||||||
self.conn.decode_result(r)
|
self.conn.decode_result(r)
|
||||||
@ -963,9 +967,9 @@ pub struct MappedRows<'stmt, 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(&SqliteRow) -> T
|
||||||
{
|
{
|
||||||
type Item = SqliteResult<T>;
|
type Item = Result<T>;
|
||||||
|
|
||||||
fn next(&mut self) -> Option<SqliteResult<T>> {
|
fn next(&mut self) -> Option<Result<T>> {
|
||||||
self.rows.next().map(|row_result| row_result.map(|row| (self.map)(&row)))
|
self.rows.next().map(|row_result| row_result.map(|row| (self.map)(&row)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -979,9 +983,9 @@ pub struct AndThenRows<'stmt, F> {
|
|||||||
|
|
||||||
impl<'stmt, T, E, F> Iterator for AndThenRows<'stmt, F>
|
impl<'stmt, T, E, F> Iterator for AndThenRows<'stmt, F>
|
||||||
where E: convert::From<Error>,
|
where E: convert::From<Error>,
|
||||||
F: FnMut(&SqliteRow) -> Result<T, E>
|
F: FnMut(&SqliteRow) -> result::Result<T, E>
|
||||||
{
|
{
|
||||||
type Item = Result<T, E>;
|
type Item = result::Result<T, E>;
|
||||||
|
|
||||||
fn next(&mut self) -> Option<Self::Item> {
|
fn next(&mut self) -> Option<Self::Item> {
|
||||||
self.rows.next().map(|row_result| {
|
self.rows.next().map(|row_result| {
|
||||||
@ -1000,8 +1004,8 @@ where E: convert::From<Error>,
|
|||||||
/// iterator). For example:
|
/// iterator). For example:
|
||||||
///
|
///
|
||||||
/// ```rust,no_run
|
/// ```rust,no_run
|
||||||
/// # use rusqlite::{Connection, SqliteResult};
|
/// # use rusqlite::{Connection, Result};
|
||||||
/// fn bad_function_will_panic(conn: &Connection) -> SqliteResult<i64> {
|
/// fn bad_function_will_panic(conn: &Connection) -> Result<i64> {
|
||||||
/// let mut stmt = try!(conn.prepare("SELECT id FROM my_table"));
|
/// let mut stmt = try!(conn.prepare("SELECT id FROM my_table"));
|
||||||
/// let mut rows = try!(stmt.query(&[]));
|
/// let mut rows = try!(stmt.query(&[]));
|
||||||
///
|
///
|
||||||
@ -1041,7 +1045,7 @@ impl<'stmt> SqliteRows<'stmt> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_expected_row(&mut self) -> SqliteResult<SqliteRow<'stmt>> {
|
fn get_expected_row(&mut self) -> Result<SqliteRow<'stmt>> {
|
||||||
match self.next() {
|
match self.next() {
|
||||||
Some(row) => row,
|
Some(row) => row,
|
||||||
None => {
|
None => {
|
||||||
@ -1055,9 +1059,9 @@ impl<'stmt> SqliteRows<'stmt> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<'stmt> Iterator for SqliteRows<'stmt> {
|
impl<'stmt> Iterator for SqliteRows<'stmt> {
|
||||||
type Item = SqliteResult<SqliteRow<'stmt>>;
|
type Item = Result<SqliteRow<'stmt>>;
|
||||||
|
|
||||||
fn next(&mut self) -> Option<SqliteResult<SqliteRow<'stmt>>> {
|
fn next(&mut self) -> Option<Result<SqliteRow<'stmt>>> {
|
||||||
if self.failed {
|
if self.failed {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
@ -1096,8 +1100,8 @@ impl<'stmt> SqliteRow<'stmt> {
|
|||||||
/// for example) this isn't an issue, but it means you cannot do something like this:
|
/// for example) this isn't an issue, but it means you cannot do something like this:
|
||||||
///
|
///
|
||||||
/// ```rust,no_run
|
/// ```rust,no_run
|
||||||
/// # use rusqlite::{Connection, SqliteResult};
|
/// # use rusqlite::{Connection, Result};
|
||||||
/// fn bad_function_will_panic(conn: &Connection) -> SqliteResult<i64> {
|
/// fn bad_function_will_panic(conn: &Connection) -> Result<i64> {
|
||||||
/// let mut stmt = try!(conn.prepare("SELECT id FROM my_table"));
|
/// let mut stmt = try!(conn.prepare("SELECT id FROM my_table"));
|
||||||
/// let mut rows = try!(stmt.query(&[]));
|
/// let mut rows = try!(stmt.query(&[]));
|
||||||
///
|
///
|
||||||
@ -1129,7 +1133,7 @@ impl<'stmt> SqliteRow<'stmt> {
|
|||||||
///
|
///
|
||||||
/// Returns a `SQLITE_MISUSE`-coded `Error` 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.
|
/// for this row or if this row is stale.
|
||||||
pub fn get_checked<T: FromSql>(&self, idx: c_int) -> SqliteResult<T> {
|
pub fn get_checked<T: FromSql>(&self, idx: c_int) -> Result<T> {
|
||||||
if self.row_idx != self.current_row.get() {
|
if self.row_idx != self.current_row.get() {
|
||||||
return Err(Error {
|
return Err(Error {
|
||||||
code: ffi::SQLITE_MISUSE,
|
code: ffi::SQLITE_MISUSE,
|
||||||
@ -1240,10 +1244,10 @@ mod test {
|
|||||||
let db = checked_memory_handle();
|
let db = checked_memory_handle();
|
||||||
db.execute_batch("CREATE TABLE foo(x INTEGER)").unwrap();
|
db.execute_batch("CREATE TABLE foo(x INTEGER)").unwrap();
|
||||||
|
|
||||||
assert_eq!(db.execute("INSERT INTO foo(x) VALUES (?)", &[&1i32]).unwrap(),
|
assert_eq!(1,
|
||||||
1);
|
db.execute("INSERT INTO foo(x) VALUES (?)", &[&1i32]).unwrap());
|
||||||
assert_eq!(db.execute("INSERT INTO foo(x) VALUES (?)", &[&2i32]).unwrap(),
|
assert_eq!(1,
|
||||||
1);
|
db.execute("INSERT INTO foo(x) VALUES (?)", &[&2i32]).unwrap());
|
||||||
|
|
||||||
assert_eq!(3i32,
|
assert_eq!(3i32,
|
||||||
db.query_row("SELECT SUM(x) FROM foo", &[], |r| r.get(0)).unwrap());
|
db.query_row("SELECT SUM(x) FROM foo", &[], |r| r.get(0)).unwrap());
|
||||||
@ -1328,7 +1332,7 @@ mod test {
|
|||||||
db.execute_batch(sql).unwrap();
|
db.execute_batch(sql).unwrap();
|
||||||
|
|
||||||
let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap();
|
let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap();
|
||||||
let results: SqliteResult<Vec<String>> = query.query_map(&[], |row| row.get(1))
|
let results: Result<Vec<String>> = query.query_map(&[], |row| row.get(1))
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
@ -1425,7 +1429,7 @@ mod test {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Display for CustomError {
|
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 {
|
match *self {
|
||||||
CustomError::SomeError => write!(f, "{}", self.description()),
|
CustomError::SomeError => write!(f, "{}", self.description()),
|
||||||
CustomError::Sqlite(ref se) => write!(f, "{}: {}", self.description(), se),
|
CustomError::Sqlite(ref se) => write!(f, "{}: {}", self.description(), se),
|
||||||
@ -1451,7 +1455,7 @@ mod test {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type CustomResult<T> = Result<T, CustomError>;
|
type CustomResult<T> = ::std::result::Result<T, CustomError>;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg_attr(rustfmt, rustfmt_skip)]
|
#[cfg_attr(rustfmt, rustfmt_skip)]
|
||||||
@ -1467,7 +1471,7 @@ mod test {
|
|||||||
db.execute_batch(sql).unwrap();
|
db.execute_batch(sql).unwrap();
|
||||||
|
|
||||||
let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap();
|
let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap();
|
||||||
let results: SqliteResult<Vec<String>> = query.query_and_then(&[],
|
let results: Result<Vec<String>> = query.query_and_then(&[],
|
||||||
|row| row.get_checked(1))
|
|row| row.get_checked(1))
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.collect();
|
.collect();
|
||||||
@ -1489,7 +1493,7 @@ mod test {
|
|||||||
db.execute_batch(sql).unwrap();
|
db.execute_batch(sql).unwrap();
|
||||||
|
|
||||||
let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap();
|
let mut query = db.prepare("SELECT x, y FROM foo ORDER BY x DESC").unwrap();
|
||||||
let bad_type: SqliteResult<Vec<f64>> = query.query_and_then(&[],
|
let bad_type: Result<Vec<f64>> = query.query_and_then(&[],
|
||||||
|row| row.get_checked(1))
|
|row| row.get_checked(1))
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.collect();
|
.collect();
|
||||||
@ -1500,7 +1504,7 @@ mod test {
|
|||||||
message: "Invalid column type".to_owned(),
|
message: "Invalid column type".to_owned(),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
let bad_idx: SqliteResult<Vec<String>> = query.query_and_then(&[],
|
let bad_idx: Result<Vec<String>> = query.query_and_then(&[],
|
||||||
|row| row.get_checked(3))
|
|row| row.get_checked(3))
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.collect();
|
.collect();
|
||||||
|
@ -1,13 +1,13 @@
|
|||||||
use {SqliteResult, Connection};
|
use {Result, Connection};
|
||||||
|
|
||||||
/// RAII guard temporarily enabling SQLite extensions to be loaded.
|
/// RAII guard temporarily enabling SQLite extensions to be loaded.
|
||||||
///
|
///
|
||||||
/// ## Example
|
/// ## Example
|
||||||
///
|
///
|
||||||
/// ```rust,no_run
|
/// ```rust,no_run
|
||||||
/// # use rusqlite::{Connection, SqliteResult, SqliteLoadExtensionGuard};
|
/// # use rusqlite::{Connection, Result, SqliteLoadExtensionGuard};
|
||||||
/// # use std::path::{Path};
|
/// # use std::path::{Path};
|
||||||
/// fn load_my_extension(conn: &Connection) -> SqliteResult<()> {
|
/// fn load_my_extension(conn: &Connection) -> Result<()> {
|
||||||
/// let _guard = try!(SqliteLoadExtensionGuard::new(conn));
|
/// let _guard = try!(SqliteLoadExtensionGuard::new(conn));
|
||||||
///
|
///
|
||||||
/// conn.load_extension(Path::new("my_sqlite_extension"), None)
|
/// conn.load_extension(Path::new("my_sqlite_extension"), None)
|
||||||
@ -20,7 +20,7 @@ pub struct SqliteLoadExtensionGuard<'conn> {
|
|||||||
impl<'conn> SqliteLoadExtensionGuard<'conn> {
|
impl<'conn> SqliteLoadExtensionGuard<'conn> {
|
||||||
/// Attempt to enable loading extensions. Loading extensions will be disabled when this
|
/// Attempt to enable loading extensions. Loading extensions will be disabled when this
|
||||||
/// guard goes out of scope. Cannot be meaningfully nested.
|
/// guard goes out of scope. Cannot be meaningfully nested.
|
||||||
pub fn new(conn: &Connection) -> SqliteResult<SqliteLoadExtensionGuard> {
|
pub fn new(conn: &Connection) -> Result<SqliteLoadExtensionGuard> {
|
||||||
conn.load_extension_enable().map(|_| SqliteLoadExtensionGuard { conn: conn })
|
conn.load_extension_enable().map(|_| SqliteLoadExtensionGuard { conn: conn })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -2,7 +2,7 @@ use libc::c_int;
|
|||||||
|
|
||||||
use super::ffi;
|
use super::ffi;
|
||||||
|
|
||||||
use {SqliteResult, Error, Connection, SqliteStatement, SqliteRows, SqliteRow,
|
use {Result, Error, Connection, SqliteStatement, SqliteRows, SqliteRow,
|
||||||
str_to_cstring};
|
str_to_cstring};
|
||||||
use types::ToSql;
|
use types::ToSql;
|
||||||
|
|
||||||
@ -15,8 +15,8 @@ impl Connection {
|
|||||||
/// ## Example
|
/// ## Example
|
||||||
///
|
///
|
||||||
/// ```rust,no_run
|
/// ```rust,no_run
|
||||||
/// # use rusqlite::{Connection, SqliteResult};
|
/// # use rusqlite::{Connection, Result};
|
||||||
/// fn insert(conn: &Connection) -> SqliteResult<i32> {
|
/// fn insert(conn: &Connection) -> Result<i32> {
|
||||||
/// conn.execute_named("INSERT INTO test (name) VALUES (:name)", &[(":name", &"one")])
|
/// conn.execute_named("INSERT INTO test (name) VALUES (:name)", &[(":name", &"one")])
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
@ -25,7 +25,7 @@ impl Connection {
|
|||||||
///
|
///
|
||||||
/// Will return `Err` if `sql` cannot be converted to a C-compatible string or if the
|
/// Will return `Err` if `sql` cannot be converted to a C-compatible string or if the
|
||||||
/// underlying SQLite call fails.
|
/// underlying SQLite call fails.
|
||||||
pub fn execute_named(&self, sql: &str, params: &[(&str, &ToSql)]) -> SqliteResult<c_int> {
|
pub fn execute_named(&self, sql: &str, params: &[(&str, &ToSql)]) -> Result<c_int> {
|
||||||
self.prepare(sql).and_then(|mut stmt| stmt.execute_named(params))
|
self.prepare(sql).and_then(|mut stmt| stmt.execute_named(params))
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -42,7 +42,7 @@ impl Connection {
|
|||||||
sql: &str,
|
sql: &str,
|
||||||
params: &[(&str, &ToSql)],
|
params: &[(&str, &ToSql)],
|
||||||
f: F)
|
f: F)
|
||||||
-> SqliteResult<T>
|
-> Result<T>
|
||||||
where F: FnOnce(SqliteRow) -> T
|
where F: FnOnce(SqliteRow) -> T
|
||||||
{
|
{
|
||||||
let mut stmt = try!(self.prepare(sql));
|
let mut stmt = try!(self.prepare(sql));
|
||||||
@ -59,7 +59,7 @@ impl<'conn> SqliteStatement<'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) -> SqliteResult<Option<i32>> {
|
pub fn parameter_index(&self, name: &str) -> Result<Option<i32>> {
|
||||||
let c_name = try!(str_to_cstring(name));
|
let c_name = try!(str_to_cstring(name));
|
||||||
let c_index = unsafe { ffi::sqlite3_bind_parameter_index(self.stmt, c_name.as_ptr()) };
|
let c_index = unsafe { ffi::sqlite3_bind_parameter_index(self.stmt, c_name.as_ptr()) };
|
||||||
Ok(match c_index {
|
Ok(match c_index {
|
||||||
@ -79,8 +79,8 @@ impl<'conn> SqliteStatement<'conn> {
|
|||||||
/// ## Example
|
/// ## Example
|
||||||
///
|
///
|
||||||
/// ```rust,no_run
|
/// ```rust,no_run
|
||||||
/// # use rusqlite::{Connection, SqliteResult};
|
/// # use rusqlite::{Connection, Result};
|
||||||
/// fn insert(conn: &Connection) -> SqliteResult<i32> {
|
/// fn insert(conn: &Connection) -> Result<i32> {
|
||||||
/// let mut stmt = try!(conn.prepare("INSERT INTO test (name) VALUES (:name)"));
|
/// let mut stmt = try!(conn.prepare("INSERT INTO test (name) VALUES (:name)"));
|
||||||
/// stmt.execute_named(&[(":name", &"one")])
|
/// stmt.execute_named(&[(":name", &"one")])
|
||||||
/// }
|
/// }
|
||||||
@ -90,7 +90,7 @@ impl<'conn> SqliteStatement<'conn> {
|
|||||||
///
|
///
|
||||||
/// Will return `Err` if binding parameters fails, the executed statement returns rows (in
|
/// 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.
|
/// which case `query` should be used instead), or the underling SQLite call fails.
|
||||||
pub fn execute_named(&mut self, params: &[(&str, &ToSql)]) -> SqliteResult<c_int> {
|
pub fn execute_named(&mut self, params: &[(&str, &ToSql)]) -> Result<c_int> {
|
||||||
try!(self.bind_parameters_named(params));
|
try!(self.bind_parameters_named(params));
|
||||||
unsafe {
|
unsafe {
|
||||||
self.execute_()
|
self.execute_()
|
||||||
@ -105,8 +105,8 @@ impl<'conn> SqliteStatement<'conn> {
|
|||||||
/// ## Example
|
/// ## Example
|
||||||
///
|
///
|
||||||
/// ```rust,no_run
|
/// ```rust,no_run
|
||||||
/// # use rusqlite::{Connection, SqliteResult, SqliteRows};
|
/// # use rusqlite::{Connection, Result, SqliteRows};
|
||||||
/// fn query(conn: &Connection) -> SqliteResult<()> {
|
/// fn query(conn: &Connection) -> Result<()> {
|
||||||
/// let mut stmt = try!(conn.prepare("SELECT * FROM test where name = :name"));
|
/// let mut stmt = try!(conn.prepare("SELECT * FROM test where name = :name"));
|
||||||
/// let mut rows = try!(stmt.query_named(&[(":name", &"one")]));
|
/// let mut rows = try!(stmt.query_named(&[(":name", &"one")]));
|
||||||
/// for row in rows {
|
/// for row in rows {
|
||||||
@ -121,7 +121,7 @@ impl<'conn> SqliteStatement<'conn> {
|
|||||||
/// Will return `Err` if binding parameters fails.
|
/// Will return `Err` if binding parameters fails.
|
||||||
pub fn query_named<'a>(&'a mut self,
|
pub fn query_named<'a>(&'a mut self,
|
||||||
params: &[(&str, &ToSql)])
|
params: &[(&str, &ToSql)])
|
||||||
-> SqliteResult<SqliteRows<'a>> {
|
-> Result<SqliteRows<'a>> {
|
||||||
self.reset_if_needed();
|
self.reset_if_needed();
|
||||||
try!(self.bind_parameters_named(params));
|
try!(self.bind_parameters_named(params));
|
||||||
|
|
||||||
@ -129,7 +129,7 @@ impl<'conn> SqliteStatement<'conn> {
|
|||||||
Ok(SqliteRows::new(self))
|
Ok(SqliteRows::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 {
|
for &(name, value) in params {
|
||||||
if let Some(i) = try!(self.parameter_index(name)) {
|
if let Some(i) = try!(self.parameter_index(name)) {
|
||||||
try!(self.conn.decode_result(unsafe { value.bind_parameter(self.stmt, i) }));
|
try!(self.conn.decode_result(unsafe { value.bind_parameter(self.stmt, i) }));
|
||||||
|
@ -8,7 +8,7 @@ use std::str;
|
|||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use super::ffi;
|
use super::ffi;
|
||||||
use {Error, SqliteResult, Connection};
|
use {Error, Result, Connection};
|
||||||
|
|
||||||
/// 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:
|
||||||
@ -21,7 +21,7 @@ use {Error, SqliteResult, Connection};
|
|||||||
/// * It must be threadsafe if SQLite is used in a multithreaded way.
|
/// * It must be threadsafe if SQLite is used in a multithreaded way.
|
||||||
///
|
///
|
||||||
/// cf [The Error And Warning Log](http://sqlite.org/errlog.html).
|
/// cf [The Error And Warning Log](http://sqlite.org/errlog.html).
|
||||||
pub unsafe fn config_log(callback: Option<fn(c_int, &str)>) -> SqliteResult<()> {
|
pub unsafe fn config_log(callback: Option<fn(c_int, &str)>) -> Result<()> {
|
||||||
extern "C" fn log_callback(p_arg: *mut c_void, err: c_int, msg: *const c_char) {
|
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 c_slice = unsafe { CStr::from_ptr(msg).to_bytes() };
|
||||||
let callback: fn(c_int, &str) = unsafe { mem::transmute(p_arg) };
|
let callback: fn(c_int, &str) = unsafe { mem::transmute(p_arg) };
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
use {SqliteResult, Connection};
|
use {Result, Connection};
|
||||||
|
|
||||||
pub use SqliteTransactionBehavior::{SqliteTransactionDeferred, SqliteTransactionImmediate,
|
pub use SqliteTransactionBehavior::{SqliteTransactionDeferred, SqliteTransactionImmediate,
|
||||||
SqliteTransactionExclusive};
|
SqliteTransactionExclusive};
|
||||||
@ -22,10 +22,10 @@ pub enum SqliteTransactionBehavior {
|
|||||||
/// ## Example
|
/// ## Example
|
||||||
///
|
///
|
||||||
/// ```rust,no_run
|
/// ```rust,no_run
|
||||||
/// # use rusqlite::{Connection, SqliteResult};
|
/// # use rusqlite::{Connection, Result};
|
||||||
/// # fn do_queries_part_1(conn: &Connection) -> SqliteResult<()> { Ok(()) }
|
/// # fn do_queries_part_1(conn: &Connection) -> Result<()> { Ok(()) }
|
||||||
/// # fn do_queries_part_2(conn: &Connection) -> SqliteResult<()> { Ok(()) }
|
/// # fn do_queries_part_2(conn: &Connection) -> Result<()> { Ok(()) }
|
||||||
/// fn perform_queries(conn: &Connection) -> SqliteResult<()> {
|
/// fn perform_queries(conn: &Connection) -> Result<()> {
|
||||||
/// let tx = try!(conn.transaction());
|
/// let tx = try!(conn.transaction());
|
||||||
///
|
///
|
||||||
/// try!(do_queries_part_1(conn)); // tx causes rollback if this fails
|
/// try!(do_queries_part_1(conn)); // tx causes rollback if this fails
|
||||||
@ -45,7 +45,7 @@ impl<'conn> SqliteTransaction<'conn> {
|
|||||||
/// Begin a new transaction. Cannot be nested; see `savepoint` for nested transactions.
|
/// Begin a new transaction. Cannot be nested; see `savepoint` for nested transactions.
|
||||||
pub fn new(conn: &Connection,
|
pub fn new(conn: &Connection,
|
||||||
behavior: SqliteTransactionBehavior)
|
behavior: SqliteTransactionBehavior)
|
||||||
-> SqliteResult<SqliteTransaction> {
|
-> Result<SqliteTransaction> {
|
||||||
let query = match behavior {
|
let query = match behavior {
|
||||||
SqliteTransactionDeferred => "BEGIN DEFERRED",
|
SqliteTransactionDeferred => "BEGIN DEFERRED",
|
||||||
SqliteTransactionImmediate => "BEGIN IMMEDIATE",
|
SqliteTransactionImmediate => "BEGIN IMMEDIATE",
|
||||||
@ -71,9 +71,9 @@ impl<'conn> SqliteTransaction<'conn> {
|
|||||||
/// ## Example
|
/// ## Example
|
||||||
///
|
///
|
||||||
/// ```rust,no_run
|
/// ```rust,no_run
|
||||||
/// # use rusqlite::{Connection, SqliteResult};
|
/// # 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: &Connection) -> SqliteResult<()> {
|
/// fn perform_queries(conn: &Connection) -> Result<()> {
|
||||||
/// let tx = try!(conn.transaction());
|
/// let tx = try!(conn.transaction());
|
||||||
///
|
///
|
||||||
/// {
|
/// {
|
||||||
@ -87,7 +87,7 @@ impl<'conn> SqliteTransaction<'conn> {
|
|||||||
/// tx.commit()
|
/// tx.commit()
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
pub fn savepoint<'a>(&'a self) -> SqliteResult<SqliteTransaction<'a>> {
|
pub fn savepoint<'a>(&'a self) -> Result<SqliteTransaction<'a>> {
|
||||||
self.conn.execute_batch("SAVEPOINT sp").map(|_| {
|
self.conn.execute_batch("SAVEPOINT sp").map(|_| {
|
||||||
SqliteTransaction {
|
SqliteTransaction {
|
||||||
conn: self.conn,
|
conn: self.conn,
|
||||||
@ -119,11 +119,11 @@ impl<'conn> SqliteTransaction<'conn> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A convenience method which consumes and commits a transaction.
|
/// A convenience method which consumes and commits a transaction.
|
||||||
pub fn commit(mut self) -> SqliteResult<()> {
|
pub fn commit(mut self) -> Result<()> {
|
||||||
self.commit_()
|
self.commit_()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn commit_(&mut self) -> SqliteResult<()> {
|
fn commit_(&mut self) -> Result<()> {
|
||||||
self.finished = true;
|
self.finished = true;
|
||||||
self.conn.execute_batch(if self.depth == 0 {
|
self.conn.execute_batch(if self.depth == 0 {
|
||||||
"COMMIT"
|
"COMMIT"
|
||||||
@ -133,11 +133,11 @@ impl<'conn> SqliteTransaction<'conn> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A convenience method which consumes and rolls back a transaction.
|
/// A convenience method which consumes and rolls back a transaction.
|
||||||
pub fn rollback(mut self) -> SqliteResult<()> {
|
pub fn rollback(mut self) -> Result<()> {
|
||||||
self.rollback_()
|
self.rollback_()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn rollback_(&mut self) -> SqliteResult<()> {
|
fn rollback_(&mut self) -> Result<()> {
|
||||||
self.finished = true;
|
self.finished = true;
|
||||||
self.conn.execute_batch(if self.depth == 0 {
|
self.conn.execute_batch(if self.depth == 0 {
|
||||||
"ROLLBACK"
|
"ROLLBACK"
|
||||||
@ -151,11 +151,11 @@ impl<'conn> SqliteTransaction<'conn> {
|
|||||||
///
|
///
|
||||||
/// Functionally equivalent to the `Drop` implementation, but allows callers to see any
|
/// Functionally equivalent to the `Drop` implementation, but allows callers to see any
|
||||||
/// errors that occur.
|
/// errors that occur.
|
||||||
pub fn finish(mut self) -> SqliteResult<()> {
|
pub fn finish(mut self) -> Result<()> {
|
||||||
self.finish_()
|
self.finish_()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn finish_(&mut self) -> SqliteResult<()> {
|
fn finish_(&mut self) -> Result<()> {
|
||||||
match (self.finished, self.commit) {
|
match (self.finished, self.commit) {
|
||||||
(true, _) => Ok(()),
|
(true, _) => Ok(()),
|
||||||
(false, true) => self.commit_(),
|
(false, true) => self.commit_(),
|
||||||
|
24
src/types.rs
24
src/types.rs
@ -26,7 +26,7 @@
|
|||||||
//! extern crate libc;
|
//! extern crate libc;
|
||||||
//!
|
//!
|
||||||
//! use rusqlite::types::{FromSql, ToSql, sqlite3_stmt};
|
//! use rusqlite::types::{FromSql, ToSql, sqlite3_stmt};
|
||||||
//! use rusqlite::{SqliteResult};
|
//! use rusqlite::{Result};
|
||||||
//! use libc::c_int;
|
//! use libc::c_int;
|
||||||
//! use time;
|
//! use time;
|
||||||
//!
|
//!
|
||||||
@ -34,7 +34,7 @@
|
|||||||
//!
|
//!
|
||||||
//! impl FromSql for TimespecSql {
|
//! impl FromSql for TimespecSql {
|
||||||
//! unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int)
|
//! unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int)
|
||||||
//! -> SqliteResult<TimespecSql> {
|
//! -> Result<TimespecSql> {
|
||||||
//! let as_f64_result = FromSql::column_result(stmt, col);
|
//! let as_f64_result = FromSql::column_result(stmt, col);
|
||||||
//! as_f64_result.map(|as_f64: f64| {
|
//! as_f64_result.map(|as_f64: f64| {
|
||||||
//! TimespecSql(time::Timespec{ sec: as_f64.trunc() as i64,
|
//! TimespecSql(time::Timespec{ sec: as_f64.trunc() as i64,
|
||||||
@ -59,7 +59,7 @@ use std::ffi::CStr;
|
|||||||
use std::mem;
|
use std::mem;
|
||||||
use std::str;
|
use std::str;
|
||||||
use super::ffi;
|
use super::ffi;
|
||||||
use super::{SqliteResult, Error, str_to_cstring};
|
use super::{Result, Error, str_to_cstring};
|
||||||
|
|
||||||
pub use ffi::sqlite3_stmt;
|
pub use ffi::sqlite3_stmt;
|
||||||
pub use ffi::sqlite3_column_type;
|
pub use ffi::sqlite3_column_type;
|
||||||
@ -75,7 +75,7 @@ pub trait ToSql {
|
|||||||
|
|
||||||
/// A trait for types that can be created from a SQLite value.
|
/// A trait for types that can be created from a SQLite value.
|
||||||
pub trait FromSql: Sized {
|
pub trait FromSql: Sized {
|
||||||
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> SqliteResult<Self>;
|
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<Self>;
|
||||||
|
|
||||||
/// FromSql types can implement this method and use sqlite3_column_type to check that
|
/// 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
|
/// the type reported by SQLite matches a type suitable for Self. This method is used
|
||||||
@ -176,12 +176,12 @@ impl<T: ToSql> ToSql for Option<T> {
|
|||||||
/// ```rust,no_run
|
/// ```rust,no_run
|
||||||
/// # extern crate libc;
|
/// # extern crate libc;
|
||||||
/// # extern crate rusqlite;
|
/// # extern crate rusqlite;
|
||||||
/// # use rusqlite::{Connection, SqliteResult};
|
/// # use rusqlite::{Connection, Result};
|
||||||
/// # use rusqlite::types::{Null};
|
/// # use rusqlite::types::{Null};
|
||||||
/// # use libc::{c_int};
|
/// # use libc::{c_int};
|
||||||
/// fn main() {
|
/// fn main() {
|
||||||
/// }
|
/// }
|
||||||
/// fn insert_null(conn: &Connection) -> SqliteResult<c_int> {
|
/// fn insert_null(conn: &Connection) -> Result<c_int> {
|
||||||
/// conn.execute("INSERT INTO people (name) VALUES (?)", &[&Null])
|
/// conn.execute("INSERT INTO people (name) VALUES (?)", &[&Null])
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
@ -197,7 +197,7 @@ impl ToSql for Null {
|
|||||||
macro_rules! raw_from_impl(
|
macro_rules! raw_from_impl(
|
||||||
($t:ty, $f:ident, $c:expr) => (
|
($t:ty, $f:ident, $c:expr) => (
|
||||||
impl FromSql for $t {
|
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))
|
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);
|
raw_from_impl!(c_double, sqlite3_column_double, ffi::SQLITE_FLOAT);
|
||||||
|
|
||||||
impl FromSql for bool {
|
impl FromSql for bool {
|
||||||
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> SqliteResult<bool> {
|
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<bool> {
|
||||||
match ffi::sqlite3_column_int(stmt, col) {
|
match ffi::sqlite3_column_int(stmt, col) {
|
||||||
0 => Ok(false),
|
0 => Ok(false),
|
||||||
_ => Ok(true),
|
_ => Ok(true),
|
||||||
@ -226,7 +226,7 @@ impl FromSql for bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl FromSql for String {
|
impl FromSql for String {
|
||||||
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> SqliteResult<String> {
|
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<String> {
|
||||||
let c_text = ffi::sqlite3_column_text(stmt, col);
|
let c_text = ffi::sqlite3_column_text(stmt, col);
|
||||||
if c_text.is_null() {
|
if c_text.is_null() {
|
||||||
Ok("".to_string())
|
Ok("".to_string())
|
||||||
@ -249,7 +249,7 @@ impl FromSql for String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl FromSql for Vec<u8> {
|
impl FromSql for Vec<u8> {
|
||||||
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> SqliteResult<Vec<u8>> {
|
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<Vec<u8>> {
|
||||||
use std::slice::from_raw_parts;
|
use std::slice::from_raw_parts;
|
||||||
let c_blob = ffi::sqlite3_column_blob(stmt, col);
|
let c_blob = ffi::sqlite3_column_blob(stmt, col);
|
||||||
let len = ffi::sqlite3_column_bytes(stmt, col);
|
let len = ffi::sqlite3_column_bytes(stmt, col);
|
||||||
@ -269,7 +269,7 @@ impl FromSql for Vec<u8> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl FromSql for time::Timespec {
|
impl FromSql for time::Timespec {
|
||||||
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> SqliteResult<time::Timespec> {
|
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<time::Timespec> {
|
||||||
let col_str = FromSql::column_result(stmt, col);
|
let col_str = FromSql::column_result(stmt, col);
|
||||||
col_str.and_then(|txt: String| {
|
col_str.and_then(|txt: String| {
|
||||||
time::strptime(&txt, SQLITE_DATETIME_FMT)
|
time::strptime(&txt, SQLITE_DATETIME_FMT)
|
||||||
@ -289,7 +289,7 @@ impl FromSql for time::Timespec {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<T: FromSql> FromSql for Option<T> {
|
impl<T: FromSql> FromSql for Option<T> {
|
||||||
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> SqliteResult<Option<T>> {
|
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<Option<T>> {
|
||||||
if sqlite3_column_type(stmt, col) == ffi::SQLITE_NULL {
|
if sqlite3_column_type(stmt, col) == ffi::SQLITE_NULL {
|
||||||
Ok(None)
|
Ok(None)
|
||||||
} else {
|
} else {
|
||||||
|
Loading…
Reference in New Issue
Block a user