mirror of
https://github.com/isar/rusqlite.git
synced 2024-11-27 03:51:38 +08:00
Merge remote-tracking branch 'jgallagher/master' into vtab
This commit is contained in:
commit
5541cb06fe
@ -1,5 +1,5 @@
|
|||||||
rusqlite contributors (sorted alphabetically)
|
rusqlite contributors
|
||||||
=============================================
|
=====================
|
||||||
|
|
||||||
* [John Gallagher](https://github.com/jgallagher)
|
* [John Gallagher](https://github.com/jgallagher)
|
||||||
* [Marcus Klaas de Vries](https://github.com/marcusklaas)
|
* [Marcus Klaas de Vries](https://github.com/marcusklaas)
|
||||||
@ -13,3 +13,4 @@ rusqlite contributors (sorted alphabetically)
|
|||||||
* [Andrew Straw](https://github.com/astraw)
|
* [Andrew Straw](https://github.com/astraw)
|
||||||
* [Ronald Kinard](https://github.com/Furyhunter)
|
* [Ronald Kinard](https://github.com/Furyhunter)
|
||||||
* [maciejkula](https://github.com/maciejkula)
|
* [maciejkula](https://github.com/maciejkula)
|
||||||
|
* [Xidorn Quan](https://github.com/upsuper)
|
||||||
|
@ -13,7 +13,7 @@ license = "MIT"
|
|||||||
name = "rusqlite"
|
name = "rusqlite"
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
load_extension = ["libsqlite3-sys/load_extension"]
|
load_extension = []
|
||||||
backup = []
|
backup = []
|
||||||
blob = []
|
blob = []
|
||||||
functions = []
|
functions = []
|
||||||
@ -25,6 +25,7 @@ csvtab = ["csv"]
|
|||||||
time = "~0.1.0"
|
time = "~0.1.0"
|
||||||
bitflags = "~0.1"
|
bitflags = "~0.1"
|
||||||
libc = "~0.2"
|
libc = "~0.2"
|
||||||
|
clippy = {version = "~0.0.58", optional = true}
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tempdir = "~0.3.4"
|
tempdir = "~0.3.4"
|
||||||
|
@ -1,5 +1,9 @@
|
|||||||
# Version UPCOMING (...)
|
# Version UPCOMING (...)
|
||||||
|
|
||||||
|
* Removes `load_extension` feature from `libsqlite3-sys`. `load_extension` is still available
|
||||||
|
on rusqlite itself.
|
||||||
|
* Fixes crash on nightly Rust when using the `trace` feature.
|
||||||
|
* Adds optional `clippy` feature and addresses issues it found.
|
||||||
* Adds `column_count()` method to `Statement` and `Row`.
|
* Adds `column_count()` method to `Statement` and `Row`.
|
||||||
* Adds `types::Value` for dynamic column types.
|
* Adds `types::Value` for dynamic column types.
|
||||||
* Adds support for user-defined aggregate functions (behind the existing `functions` Cargo feature).
|
* Adds support for user-defined aggregate functions (behind the existing `functions` Cargo feature).
|
||||||
|
@ -8,9 +8,6 @@ license = "MIT"
|
|||||||
links = "sqlite3"
|
links = "sqlite3"
|
||||||
build = "build.rs"
|
build = "build.rs"
|
||||||
|
|
||||||
[features]
|
|
||||||
load_extension = []
|
|
||||||
|
|
||||||
[build-dependencies]
|
[build-dependencies]
|
||||||
pkg-config = "~0.3"
|
pkg-config = "~0.3"
|
||||||
|
|
||||||
|
109
src/error.rs
109
src/error.rs
@ -88,90 +88,93 @@ impl From<::std::ffi::NulError> for Error {
|
|||||||
|
|
||||||
impl fmt::Display for Error {
|
impl fmt::Display for Error {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
match self {
|
match *self {
|
||||||
&Error::SqliteFailure(ref err, None) => err.fmt(f),
|
Error::SqliteFailure(ref err, None) => err.fmt(f),
|
||||||
&Error::SqliteFailure(_, Some(ref s)) => write!(f, "{}", s),
|
Error::SqliteFailure(_, Some(ref s)) => write!(f, "{}", s),
|
||||||
&Error::SqliteSingleThreadedMode => {
|
Error::SqliteSingleThreadedMode => {
|
||||||
write!(f,
|
write!(f,
|
||||||
"SQLite was compiled or configured for single-threaded use only")
|
"SQLite was compiled or configured for single-threaded use only")
|
||||||
}
|
}
|
||||||
&Error::FromSqlConversionFailure(ref err) => err.fmt(f),
|
Error::FromSqlConversionFailure(ref err) => err.fmt(f),
|
||||||
&Error::Utf8Error(ref err) => err.fmt(f),
|
Error::Utf8Error(ref err) => err.fmt(f),
|
||||||
&Error::NulError(ref err) => err.fmt(f),
|
Error::NulError(ref err) => err.fmt(f),
|
||||||
&Error::InvalidParameterName(ref name) => write!(f, "Invalid parameter name: {}", name),
|
Error::InvalidParameterName(ref name) => write!(f, "Invalid parameter name: {}", name),
|
||||||
&Error::InvalidPath(ref p) => write!(f, "Invalid path: {}", p.to_string_lossy()),
|
Error::InvalidPath(ref p) => write!(f, "Invalid path: {}", p.to_string_lossy()),
|
||||||
&Error::ExecuteReturnedResults => {
|
Error::ExecuteReturnedResults => {
|
||||||
write!(f, "Execute returned results - did you mean to call query?")
|
write!(f, "Execute returned results - did you mean to call query?")
|
||||||
}
|
}
|
||||||
&Error::QueryReturnedNoRows => write!(f, "Query returned no rows"),
|
Error::QueryReturnedNoRows => write!(f, "Query returned no rows"),
|
||||||
&Error::GetFromStaleRow => write!(f, "Attempted to get a value from a stale row"),
|
Error::GetFromStaleRow => write!(f, "Attempted to get a value from a stale row"),
|
||||||
&Error::InvalidColumnIndex(i) => write!(f, "Invalid column index: {}", i),
|
Error::InvalidColumnIndex(i) => write!(f, "Invalid column index: {}", i),
|
||||||
&Error::InvalidColumnName(ref name) => write!(f, "Invalid column name: {}", name),
|
Error::InvalidColumnName(ref name) => write!(f, "Invalid column name: {}", name),
|
||||||
&Error::InvalidColumnType => write!(f, "Invalid column type"),
|
Error::InvalidColumnType => write!(f, "Invalid column type"),
|
||||||
|
|
||||||
#[cfg(feature = "functions")]
|
#[cfg(feature = "functions")]
|
||||||
&Error::InvalidFunctionParameterType => write!(f, "Invalid function parameter type"),
|
Error::InvalidFunctionParameterType => write!(f, "Invalid function parameter type"),
|
||||||
#[cfg(feature = "functions")]
|
#[cfg(feature = "functions")]
|
||||||
&Error::UserFunctionError(ref err) => err.fmt(f),
|
Error::UserFunctionError(ref err) => err.fmt(f),
|
||||||
#[cfg(feature = "vtab")]
|
#[cfg(feature = "vtab")]
|
||||||
&Error::ModuleError(ref desc) => write!(f, "{}", desc),
|
Error::ModuleError(ref desc) => write!(f, "{}", desc),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl error::Error for Error {
|
impl error::Error for Error {
|
||||||
fn description(&self) -> &str {
|
fn description(&self) -> &str {
|
||||||
match self {
|
match *self {
|
||||||
&Error::SqliteFailure(ref err, None) => err.description(),
|
Error::SqliteFailure(ref err, None) => err.description(),
|
||||||
&Error::SqliteFailure(_, Some(ref s)) => s,
|
Error::SqliteFailure(_, Some(ref s)) => s,
|
||||||
&Error::SqliteSingleThreadedMode => {
|
Error::SqliteSingleThreadedMode => {
|
||||||
"SQLite was compiled or configured for single-threaded use only"
|
"SQLite was compiled or configured for single-threaded use only"
|
||||||
}
|
}
|
||||||
&Error::FromSqlConversionFailure(ref err) => err.description(),
|
Error::FromSqlConversionFailure(ref err) => err.description(),
|
||||||
&Error::Utf8Error(ref err) => err.description(),
|
Error::Utf8Error(ref err) => err.description(),
|
||||||
&Error::InvalidParameterName(_) => "invalid parameter name",
|
Error::InvalidParameterName(_) => "invalid parameter name",
|
||||||
&Error::NulError(ref err) => err.description(),
|
Error::NulError(ref err) => err.description(),
|
||||||
&Error::InvalidPath(_) => "invalid path",
|
Error::InvalidPath(_) => "invalid path",
|
||||||
&Error::ExecuteReturnedResults => {
|
Error::ExecuteReturnedResults => {
|
||||||
"execute returned results - did you mean to call query?"
|
"execute returned results - did you mean to call query?"
|
||||||
}
|
}
|
||||||
&Error::QueryReturnedNoRows => "query returned no rows",
|
Error::QueryReturnedNoRows => "query returned no rows",
|
||||||
&Error::GetFromStaleRow => "attempted to get a value from a stale row",
|
Error::GetFromStaleRow => "attempted to get a value from a stale row",
|
||||||
&Error::InvalidColumnIndex(_) => "invalid column index",
|
Error::InvalidColumnIndex(_) => "invalid column index",
|
||||||
&Error::InvalidColumnName(_) => "invalid column name",
|
Error::InvalidColumnName(_) => "invalid column name",
|
||||||
&Error::InvalidColumnType => "invalid column type",
|
Error::InvalidColumnType => "invalid column type",
|
||||||
|
|
||||||
#[cfg(feature = "functions")]
|
#[cfg(feature = "functions")]
|
||||||
&Error::InvalidFunctionParameterType => "invalid function parameter type",
|
Error::InvalidFunctionParameterType => "invalid function parameter type",
|
||||||
#[cfg(feature = "functions")]
|
#[cfg(feature = "functions")]
|
||||||
&Error::UserFunctionError(ref err) => err.description(),
|
Error::UserFunctionError(ref err) => err.description(),
|
||||||
#[cfg(feature = "vtab")]
|
#[cfg(feature = "vtab")]
|
||||||
&Error::ModuleError(ref desc) => desc,
|
Error::ModuleError(ref desc) => desc,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg_attr(feature="clippy", allow(match_same_arms))]
|
||||||
fn cause(&self) -> Option<&error::Error> {
|
fn cause(&self) -> Option<&error::Error> {
|
||||||
match self {
|
match *self {
|
||||||
&Error::SqliteFailure(ref err, _) => Some(err),
|
Error::SqliteFailure(ref err, _) => Some(err),
|
||||||
&Error::SqliteSingleThreadedMode => None,
|
Error::FromSqlConversionFailure(ref err) => Some(&**err),
|
||||||
&Error::FromSqlConversionFailure(ref err) => Some(&**err),
|
Error::Utf8Error(ref err) => Some(err),
|
||||||
&Error::Utf8Error(ref err) => Some(err),
|
Error::NulError(ref err) => Some(err),
|
||||||
&Error::NulError(ref err) => Some(err),
|
|
||||||
&Error::InvalidParameterName(_) => None,
|
Error::SqliteSingleThreadedMode |
|
||||||
&Error::InvalidPath(_) => None,
|
Error::InvalidParameterName(_) |
|
||||||
&Error::ExecuteReturnedResults => None,
|
Error::ExecuteReturnedResults |
|
||||||
&Error::QueryReturnedNoRows => None,
|
Error::QueryReturnedNoRows |
|
||||||
&Error::GetFromStaleRow => None,
|
Error::GetFromStaleRow |
|
||||||
&Error::InvalidColumnIndex(_) => None,
|
Error::InvalidColumnIndex(_) |
|
||||||
&Error::InvalidColumnName(_) => None,
|
Error::InvalidColumnName(_) |
|
||||||
&Error::InvalidColumnType => None,
|
Error::InvalidColumnType |
|
||||||
|
Error::InvalidPath(_) => None,
|
||||||
|
|
||||||
#[cfg(feature = "functions")]
|
#[cfg(feature = "functions")]
|
||||||
&Error::InvalidFunctionParameterType => None,
|
Error::InvalidFunctionParameterType => None,
|
||||||
|
|
||||||
#[cfg(feature = "functions")]
|
#[cfg(feature = "functions")]
|
||||||
&Error::UserFunctionError(ref err) => Some(&**err),
|
Error::UserFunctionError(ref err) => Some(&**err),
|
||||||
#[cfg(feature = "vtab")]
|
#[cfg(feature = "vtab")]
|
||||||
&Error::ModuleError(_) => None,
|
Error::ModuleError(_) => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -88,9 +88,10 @@ raw_to_impl!(c_double, sqlite3_result_double);
|
|||||||
|
|
||||||
impl<'a> ToResult for bool {
|
impl<'a> ToResult for bool {
|
||||||
unsafe fn set_result(&self, ctx: *mut sqlite3_context) {
|
unsafe fn set_result(&self, ctx: *mut sqlite3_context) {
|
||||||
match *self {
|
if *self {
|
||||||
true => ffi::sqlite3_result_int(ctx, 1),
|
ffi::sqlite3_result_int(ctx, 1)
|
||||||
_ => ffi::sqlite3_result_int(ctx, 0),
|
} else {
|
||||||
|
ffi::sqlite3_result_int(ctx, 0)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -234,7 +235,7 @@ impl FromValue for String {
|
|||||||
unsafe fn parameter_value(v: *mut sqlite3_value) -> Result<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_owned())
|
||||||
} else {
|
} else {
|
||||||
let c_slice = CStr::from_ptr(c_text as *const c_char).to_bytes();
|
let c_slice = CStr::from_ptr(c_text as *const c_char).to_bytes();
|
||||||
let utf8_str = try!(str::from_utf8(c_slice));
|
let utf8_str = try!(str::from_utf8(c_slice));
|
||||||
@ -270,7 +271,7 @@ impl<T: FromValue> FromValue for Option<T> {
|
|||||||
if sqlite3_value_type(v) == ffi::SQLITE_NULL {
|
if sqlite3_value_type(v) == ffi::SQLITE_NULL {
|
||||||
Ok(None)
|
Ok(None)
|
||||||
} else {
|
} else {
|
||||||
FromValue::parameter_value(v).map(|t| Some(t))
|
FromValue::parameter_value(v).map(Some)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -294,6 +295,10 @@ impl<'a> Context<'a> {
|
|||||||
pub fn len(&self) -> usize {
|
pub fn len(&self) -> usize {
|
||||||
self.args.len()
|
self.args.len()
|
||||||
}
|
}
|
||||||
|
/// Returns `true` when there is no argument.
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.args.is_empty()
|
||||||
|
}
|
||||||
|
|
||||||
/// Returns the `idx`th argument as a `T`.
|
/// Returns the `idx`th argument as a `T`.
|
||||||
///
|
///
|
||||||
@ -322,7 +327,7 @@ impl<'a> Context<'a> {
|
|||||||
ffi::sqlite3_set_auxdata(self.ctx,
|
ffi::sqlite3_set_auxdata(self.ctx,
|
||||||
arg,
|
arg,
|
||||||
mem::transmute(boxed),
|
mem::transmute(boxed),
|
||||||
Some(mem::transmute(free_boxed_value::<T>)))
|
Some(free_boxed_value::<T>))
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -495,7 +500,7 @@ impl InnerConnection {
|
|||||||
Some(call_boxed_closure::<F, T>),
|
Some(call_boxed_closure::<F, T>),
|
||||||
None,
|
None,
|
||||||
None,
|
None,
|
||||||
Some(mem::transmute(free_boxed_value::<F>)))
|
Some(free_boxed_value::<F>))
|
||||||
};
|
};
|
||||||
self.decode_result(r)
|
self.decode_result(r)
|
||||||
}
|
}
|
||||||
@ -612,7 +617,7 @@ impl InnerConnection {
|
|||||||
None,
|
None,
|
||||||
Some(call_boxed_step::<A, D, T>),
|
Some(call_boxed_step::<A, D, T>),
|
||||||
Some(call_boxed_final::<A, D, T>),
|
Some(call_boxed_final::<A, D, T>),
|
||||||
Some(mem::transmute(free_boxed_value::<D>)))
|
Some(free_boxed_value::<D>))
|
||||||
};
|
};
|
||||||
self.decode_result(r)
|
self.decode_result(r)
|
||||||
}
|
}
|
||||||
@ -641,6 +646,7 @@ mod test {
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use libc::c_double;
|
use libc::c_double;
|
||||||
use self::regex::Regex;
|
use self::regex::Regex;
|
||||||
|
use std::f64::EPSILON;
|
||||||
|
|
||||||
use {Connection, Error, Result};
|
use {Connection, Error, Result};
|
||||||
use functions::{Aggregate, Context};
|
use functions::{Aggregate, Context};
|
||||||
@ -657,7 +663,7 @@ mod test {
|
|||||||
db.create_scalar_function("half", 1, true, half).unwrap();
|
db.create_scalar_function("half", 1, true, half).unwrap();
|
||||||
let result: Result<f64> = db.query_row("SELECT half(6)", &[], |r| r.get(0));
|
let result: Result<f64> = db.query_row("SELECT half(6)", &[], |r| r.get(0));
|
||||||
|
|
||||||
assert_eq!(3f64, result.unwrap());
|
assert!((3f64 - result.unwrap()).abs() < EPSILON);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@ -665,7 +671,7 @@ mod test {
|
|||||||
let db = Connection::open_in_memory().unwrap();
|
let db = Connection::open_in_memory().unwrap();
|
||||||
db.create_scalar_function("half", 1, true, half).unwrap();
|
db.create_scalar_function("half", 1, true, half).unwrap();
|
||||||
let result: Result<f64> = db.query_row("SELECT half(6)", &[], |r| r.get(0));
|
let result: Result<f64> = db.query_row("SELECT half(6)", &[], |r| r.get(0));
|
||||||
assert_eq!(3f64, result.unwrap());
|
assert!((3f64 - result.unwrap()).abs() < EPSILON);
|
||||||
|
|
||||||
db.remove_function("half", 1).unwrap();
|
db.remove_function("half", 1).unwrap();
|
||||||
let result: Result<f64> = db.query_row("SELECT half(6)", &[], |r| r.get(0));
|
let result: Result<f64> = db.query_row("SELECT half(6)", &[], |r| r.get(0));
|
||||||
|
34
src/lib.rs
34
src/lib.rs
@ -50,6 +50,9 @@
|
|||||||
//! }
|
//! }
|
||||||
//! }
|
//! }
|
||||||
//! ```
|
//! ```
|
||||||
|
#![cfg_attr(feature="clippy", feature(plugin))]
|
||||||
|
#![cfg_attr(feature="clippy", plugin(clippy))]
|
||||||
|
|
||||||
extern crate libc;
|
extern crate libc;
|
||||||
extern crate libsqlite3_sys as ffi;
|
extern crate libsqlite3_sys as ffi;
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
@ -100,7 +103,7 @@ 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();
|
||||||
let utf8_str = str::from_utf8(c_slice);
|
let utf8_str = str::from_utf8(c_slice);
|
||||||
utf8_str.unwrap_or("Invalid string encoding").to_string()
|
utf8_str.unwrap_or("Invalid string encoding").to_owned()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn str_to_cstring(s: &str) -> Result<CString> {
|
fn str_to_cstring(s: &str) -> Result<CString> {
|
||||||
@ -128,9 +131,9 @@ pub enum DatabaseName<'a> {
|
|||||||
// impl to avoid dead code warnings.
|
// impl to avoid dead code warnings.
|
||||||
#[cfg(any(feature = "backup", feature = "blob"))]
|
#[cfg(any(feature = "backup", feature = "blob"))]
|
||||||
impl<'a> DatabaseName<'a> {
|
impl<'a> DatabaseName<'a> {
|
||||||
fn to_cstring(self) -> Result<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"),
|
||||||
Temp => str_to_cstring("temp"),
|
Temp => str_to_cstring("temp"),
|
||||||
Attached(s) => str_to_cstring(s),
|
Attached(s) => str_to_cstring(s),
|
||||||
@ -235,7 +238,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) -> Result<Transaction<'a>> {
|
pub fn transaction(&self) -> Result<Transaction> {
|
||||||
Transaction::new(self, TransactionBehavior::Deferred)
|
Transaction::new(self, TransactionBehavior::Deferred)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -246,9 +249,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_with_behavior<'a>(&'a self,
|
pub fn transaction_with_behavior(&self, behavior: TransactionBehavior) -> Result<Transaction> {
|
||||||
behavior: TransactionBehavior)
|
|
||||||
-> Result<Transaction<'a>> {
|
|
||||||
Transaction::new(self, behavior)
|
Transaction::new(self, behavior)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -573,11 +574,7 @@ impl InnerConnection {
|
|||||||
// https://github.com/mackyle/sqlite/blob/master/src/mutex_noop.c).
|
// https://github.com/mackyle/sqlite/blob/master/src/mutex_noop.c).
|
||||||
const SQLITE_SINGLETHREADED_MUTEX_MAGIC: usize = 8;
|
const SQLITE_SINGLETHREADED_MUTEX_MAGIC: usize = 8;
|
||||||
let mutex_ptr = ffi::sqlite3_mutex_alloc(0);
|
let mutex_ptr = ffi::sqlite3_mutex_alloc(0);
|
||||||
let is_singlethreaded = if mutex_ptr as usize == SQLITE_SINGLETHREADED_MUTEX_MAGIC {
|
let is_singlethreaded = mutex_ptr as usize == SQLITE_SINGLETHREADED_MUTEX_MAGIC;
|
||||||
true
|
|
||||||
} else {
|
|
||||||
false
|
|
||||||
};
|
|
||||||
ffi::sqlite3_mutex_free(mutex_ptr);
|
ffi::sqlite3_mutex_free(mutex_ptr);
|
||||||
if is_singlethreaded {
|
if is_singlethreaded {
|
||||||
return Err(Error::SqliteSingleThreadedMode);
|
return Err(Error::SqliteSingleThreadedMode);
|
||||||
@ -795,10 +792,10 @@ impl<'conn> Statement<'conn> {
|
|||||||
ffi::sqlite3_reset(self.stmt);
|
ffi::sqlite3_reset(self.stmt);
|
||||||
match r {
|
match r {
|
||||||
ffi::SQLITE_DONE => {
|
ffi::SQLITE_DONE => {
|
||||||
if self.column_count != 0 {
|
if self.column_count == 0 {
|
||||||
Err(Error::ExecuteReturnedResults)
|
|
||||||
} else {
|
|
||||||
Ok(self.conn.changes())
|
Ok(self.conn.changes())
|
||||||
|
} else {
|
||||||
|
Err(Error::ExecuteReturnedResults)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ffi::SQLITE_ROW => Err(Error::ExecuteReturnedResults),
|
ffi::SQLITE_ROW => Err(Error::ExecuteReturnedResults),
|
||||||
@ -1174,9 +1171,9 @@ impl<'a> RowIndex for &'a str {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod test {
|
||||||
extern crate libsqlite3_sys as ffi;
|
|
||||||
extern crate tempdir;
|
extern crate tempdir;
|
||||||
pub use super::*;
|
pub use super::*;
|
||||||
|
use ffi;
|
||||||
use self::tempdir::TempDir;
|
use self::tempdir::TempDir;
|
||||||
pub use std::error::Error as StdError;
|
pub use std::error::Error as StdError;
|
||||||
pub use std::fmt;
|
pub use std::fmt;
|
||||||
@ -1225,10 +1222,9 @@ mod test {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_open_with_flags() {
|
fn test_open_with_flags() {
|
||||||
for bad_flags in [OpenFlags::empty(),
|
for bad_flags in &[OpenFlags::empty(),
|
||||||
SQLITE_OPEN_READ_ONLY | SQLITE_OPEN_READ_WRITE,
|
SQLITE_OPEN_READ_ONLY | SQLITE_OPEN_READ_WRITE,
|
||||||
SQLITE_OPEN_READ_ONLY | SQLITE_OPEN_CREATE]
|
SQLITE_OPEN_READ_ONLY | SQLITE_OPEN_CREATE] {
|
||||||
.iter() {
|
|
||||||
assert!(Connection::open_in_memory_with_flags(*bad_flags).is_err());
|
assert!(Connection::open_in_memory_with_flags(*bad_flags).is_err());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -35,7 +35,9 @@ pub unsafe fn config_log(callback: Option<fn(c_int, &str)>) -> Result<()> {
|
|||||||
let rc = match callback {
|
let rc = match callback {
|
||||||
Some(f) => {
|
Some(f) => {
|
||||||
let p_arg: *mut c_void = mem::transmute(f);
|
let p_arg: *mut c_void = mem::transmute(f);
|
||||||
ffi::sqlite3_config(ffi::SQLITE_CONFIG_LOG, Some(log_callback), p_arg)
|
ffi::sqlite3_config(ffi::SQLITE_CONFIG_LOG,
|
||||||
|
log_callback as extern "C" fn(_, _, _),
|
||||||
|
p_arg)
|
||||||
}
|
}
|
||||||
None => {
|
None => {
|
||||||
let nullptr: *mut c_void = ptr::null_mut();
|
let nullptr: *mut c_void = ptr::null_mut();
|
||||||
|
@ -89,7 +89,7 @@ impl<'conn> Transaction<'conn> {
|
|||||||
/// tx.commit()
|
/// tx.commit()
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
pub fn savepoint<'a>(&'a self) -> Result<Transaction<'a>> {
|
pub fn savepoint(&self) -> Result<Transaction> {
|
||||||
self.conn.execute_batch("SAVEPOINT sp").map(|_| {
|
self.conn.execute_batch("SAVEPOINT sp").map(|_| {
|
||||||
Transaction {
|
Transaction {
|
||||||
conn: self.conn,
|
conn: self.conn,
|
||||||
@ -174,6 +174,7 @@ impl<'conn> Drop for Transaction<'conn> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
#[cfg_attr(feature="clippy", allow(similar_names))]
|
||||||
mod test {
|
mod test {
|
||||||
use Connection;
|
use Connection;
|
||||||
|
|
||||||
|
27
src/types.rs
27
src/types.rs
@ -102,9 +102,10 @@ raw_to_impl!(c_double, sqlite3_bind_double);
|
|||||||
|
|
||||||
impl ToSql for bool {
|
impl ToSql for bool {
|
||||||
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
|
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
|
||||||
match *self {
|
if *self {
|
||||||
true => ffi::sqlite3_bind_int(stmt, col, 1),
|
ffi::sqlite3_bind_int(stmt, col, 1)
|
||||||
_ => ffi::sqlite3_bind_int(stmt, col, 0),
|
} else {
|
||||||
|
ffi::sqlite3_bind_int(stmt, col, 0)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -229,7 +230,7 @@ impl FromSql for String {
|
|||||||
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<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_owned())
|
||||||
} else {
|
} else {
|
||||||
let c_slice = CStr::from_ptr(c_text as *const c_char).to_bytes();
|
let c_slice = CStr::from_ptr(c_text as *const c_char).to_bytes();
|
||||||
let utf8_str = try!(str::from_utf8(c_slice));
|
let utf8_str = try!(str::from_utf8(c_slice));
|
||||||
@ -283,7 +284,7 @@ impl<T: FromSql> FromSql for 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 {
|
||||||
FromSql::column_result(stmt, col).map(|t| Some(t))
|
FromSql::column_result(stmt, col).map(Some)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -312,11 +313,11 @@ pub enum Value {
|
|||||||
impl FromSql for Value {
|
impl FromSql for Value {
|
||||||
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<Value> {
|
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<Value> {
|
||||||
match sqlite3_column_type(stmt, col) {
|
match sqlite3_column_type(stmt, col) {
|
||||||
ffi::SQLITE_TEXT => FromSql::column_result(stmt, col).map(|t| Value::Text(t)),
|
ffi::SQLITE_TEXT => FromSql::column_result(stmt, col).map(Value::Text),
|
||||||
ffi::SQLITE_INTEGER => Ok(Value::Integer(ffi::sqlite3_column_int64(stmt, col))),
|
ffi::SQLITE_INTEGER => Ok(Value::Integer(ffi::sqlite3_column_int64(stmt, col))),
|
||||||
ffi::SQLITE_FLOAT => Ok(Value::Real(ffi::sqlite3_column_double(stmt, col))),
|
ffi::SQLITE_FLOAT => Ok(Value::Real(ffi::sqlite3_column_double(stmt, col))),
|
||||||
ffi::SQLITE_NULL => Ok(Value::Null),
|
ffi::SQLITE_NULL => Ok(Value::Null),
|
||||||
ffi::SQLITE_BLOB => FromSql::column_result(stmt, col).map(|t| Value::Blob(t)),
|
ffi::SQLITE_BLOB => FromSql::column_result(stmt, col).map(Value::Blob),
|
||||||
_ => Err(Error::InvalidColumnType),
|
_ => Err(Error::InvalidColumnType),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -327,11 +328,13 @@ impl FromSql for Value {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
#[cfg_attr(feature="clippy", allow(similar_names))]
|
||||||
mod test {
|
mod test {
|
||||||
use Connection;
|
use Connection;
|
||||||
use super::time;
|
use super::time;
|
||||||
use Error;
|
use Error;
|
||||||
use libc::{c_int, c_double};
|
use libc::{c_int, c_double};
|
||||||
|
use std::f64::EPSILON;
|
||||||
|
|
||||||
fn checked_memory_handle() -> Connection {
|
fn checked_memory_handle() -> Connection {
|
||||||
let db = Connection::open_in_memory().unwrap();
|
let db = Connection::open_in_memory().unwrap();
|
||||||
@ -355,7 +358,7 @@ mod test {
|
|||||||
let db = checked_memory_handle();
|
let db = checked_memory_handle();
|
||||||
|
|
||||||
let s = "hello, world!";
|
let s = "hello, world!";
|
||||||
db.execute("INSERT INTO foo(t) VALUES (?)", &[&s.to_string()]).unwrap();
|
db.execute("INSERT INTO foo(t) VALUES (?)", &[&s.to_owned()]).unwrap();
|
||||||
|
|
||||||
let from: String = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap();
|
let from: String = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap();
|
||||||
assert_eq!(from, s);
|
assert_eq!(from, s);
|
||||||
@ -402,6 +405,7 @@ mod test {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
#[cfg_attr(feature="clippy", allow(cyclomatic_complexity))]
|
||||||
fn test_mismatched_types() {
|
fn test_mismatched_types() {
|
||||||
fn is_invalid_column_type(err: Error) -> bool {
|
fn is_invalid_column_type(err: Error) -> bool {
|
||||||
match err {
|
match err {
|
||||||
@ -425,7 +429,7 @@ mod test {
|
|||||||
assert_eq!(vec![1, 2], row.get_checked::<i32, Vec<u8>>(0).unwrap());
|
assert_eq!(vec![1, 2], row.get_checked::<i32, Vec<u8>>(0).unwrap());
|
||||||
assert_eq!("text", row.get_checked::<i32, String>(1).unwrap());
|
assert_eq!("text", row.get_checked::<i32, String>(1).unwrap());
|
||||||
assert_eq!(1, row.get_checked::<i32, c_int>(2).unwrap());
|
assert_eq!(1, row.get_checked::<i32, c_int>(2).unwrap());
|
||||||
assert_eq!(1.5, row.get_checked::<i32, c_double>(3).unwrap());
|
assert!((1.5 - row.get_checked::<i32, c_double>(3).unwrap()).abs() < EPSILON);
|
||||||
assert!(row.get_checked::<i32, Option<c_int>>(4).unwrap().is_none());
|
assert!(row.get_checked::<i32, Option<c_int>>(4).unwrap().is_none());
|
||||||
assert!(row.get_checked::<i32, Option<c_double>>(4).unwrap().is_none());
|
assert!(row.get_checked::<i32, Option<c_double>>(4).unwrap().is_none());
|
||||||
assert!(row.get_checked::<i32, Option<String>>(4).unwrap().is_none());
|
assert!(row.get_checked::<i32, Option<String>>(4).unwrap().is_none());
|
||||||
@ -490,7 +494,10 @@ mod test {
|
|||||||
assert_eq!(Value::Text(String::from("text")),
|
assert_eq!(Value::Text(String::from("text")),
|
||||||
row.get_checked::<i32, Value>(1).unwrap());
|
row.get_checked::<i32, Value>(1).unwrap());
|
||||||
assert_eq!(Value::Integer(1), row.get_checked::<i32, Value>(2).unwrap());
|
assert_eq!(Value::Integer(1), row.get_checked::<i32, Value>(2).unwrap());
|
||||||
assert_eq!(Value::Real(1.5), row.get_checked::<i32, Value>(3).unwrap());
|
match row.get_checked::<i32, Value>(3).unwrap() {
|
||||||
|
Value::Real(val) => assert!((1.5 - val).abs() < EPSILON),
|
||||||
|
x => panic!("Invalid Value {:?}", x),
|
||||||
|
}
|
||||||
assert_eq!(Value::Null, row.get_checked::<i32, Value>(4).unwrap());
|
assert_eq!(Value::Null, row.get_checked::<i32, Value>(4).unwrap());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user