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
3eb3b22ad5
@ -1,3 +1,9 @@
|
|||||||
|
# Version UPCOMING (...)
|
||||||
|
|
||||||
|
* BREAKING CHANGE: The `FromSql` trait has been redesigned. It now requires a single, safe
|
||||||
|
method instead of the previous definition which required implementing one or two unsafe
|
||||||
|
methods.
|
||||||
|
|
||||||
# Version 0.7.2 (2016-05-19)
|
# Version 0.7.2 (2016-05-19)
|
||||||
|
|
||||||
* BREAKING CHANGE: `Rows` no longer implements `Iterator`. It still has a `next()` method, but
|
* BREAKING CHANGE: `Rows` no longer implements `Iterator`. It still has a `next()` method, but
|
||||||
|
130
src/functions.rs
130
src/functions.rs
@ -54,7 +54,6 @@ use std::ffi::CStr;
|
|||||||
use std::mem;
|
use std::mem;
|
||||||
use std::ptr;
|
use std::ptr;
|
||||||
use std::slice;
|
use std::slice;
|
||||||
use std::str;
|
|
||||||
use libc::{c_int, c_double, c_char, c_void};
|
use libc::{c_int, c_double, c_char, c_void};
|
||||||
|
|
||||||
use ffi;
|
use ffi;
|
||||||
@ -63,7 +62,7 @@ pub use ffi::sqlite3_value;
|
|||||||
pub use ffi::sqlite3_value_type;
|
pub use ffi::sqlite3_value_type;
|
||||||
pub use ffi::sqlite3_value_numeric_type;
|
pub use ffi::sqlite3_value_numeric_type;
|
||||||
|
|
||||||
use types::Null;
|
use types::{Null, FromSql, ValueRef};
|
||||||
|
|
||||||
use {Result, Error, Connection, str_to_cstring, InnerConnection};
|
use {Result, Error, Connection, str_to_cstring, InnerConnection};
|
||||||
|
|
||||||
@ -177,107 +176,34 @@ impl ToResult for TooBig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A trait for types that can be created from a SQLite function parameter value.
|
impl<'a> ValueRef<'a> {
|
||||||
pub trait FromValue: Sized {
|
unsafe fn from_value(value: *mut sqlite3_value) -> ValueRef<'a> {
|
||||||
unsafe fn parameter_value(v: *mut sqlite3_value) -> Result<Self>;
|
|
||||||
|
|
||||||
/// 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
|
|
||||||
/// by `Context::get` to confirm that the parameter contains a valid type before
|
|
||||||
/// attempting to retrieve the value.
|
|
||||||
unsafe fn parameter_has_valid_sqlite_type(_: *mut sqlite3_value) -> bool {
|
|
||||||
true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
macro_rules! raw_from_impl(
|
|
||||||
($t:ty, $f:ident, $c:expr) => (
|
|
||||||
impl FromValue for $t {
|
|
||||||
unsafe fn parameter_value(v: *mut sqlite3_value) -> Result<$t> {
|
|
||||||
Ok(ffi::$f(v))
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe fn parameter_has_valid_sqlite_type(v: *mut sqlite3_value) -> bool {
|
|
||||||
sqlite3_value_numeric_type(v) == $c
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
raw_from_impl!(c_int, sqlite3_value_int, ffi::SQLITE_INTEGER);
|
|
||||||
raw_from_impl!(i64, sqlite3_value_int64, ffi::SQLITE_INTEGER);
|
|
||||||
|
|
||||||
impl FromValue for bool {
|
|
||||||
unsafe fn parameter_value(v: *mut sqlite3_value) -> Result<bool> {
|
|
||||||
match ffi::sqlite3_value_int(v) {
|
|
||||||
0 => Ok(false),
|
|
||||||
_ => Ok(true),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe fn parameter_has_valid_sqlite_type(v: *mut sqlite3_value) -> bool {
|
|
||||||
sqlite3_value_numeric_type(v) == ffi::SQLITE_INTEGER
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl FromValue for c_double {
|
|
||||||
unsafe fn parameter_value(v: *mut sqlite3_value) -> Result<c_double> {
|
|
||||||
Ok(ffi::sqlite3_value_double(v))
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe fn parameter_has_valid_sqlite_type(v: *mut sqlite3_value) -> bool {
|
|
||||||
sqlite3_value_numeric_type(v) == ffi::SQLITE_FLOAT ||
|
|
||||||
sqlite3_value_numeric_type(v) == ffi::SQLITE_INTEGER
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl FromValue for String {
|
|
||||||
unsafe fn parameter_value(v: *mut sqlite3_value) -> Result<String> {
|
|
||||||
let c_text = ffi::sqlite3_value_text(v);
|
|
||||||
if c_text.is_null() {
|
|
||||||
Ok("".to_owned())
|
|
||||||
} else {
|
|
||||||
let c_slice = CStr::from_ptr(c_text as *const c_char).to_bytes();
|
|
||||||
let utf8_str = try!(str::from_utf8(c_slice));
|
|
||||||
Ok(utf8_str.into())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe fn parameter_has_valid_sqlite_type(v: *mut sqlite3_value) -> bool {
|
|
||||||
sqlite3_value_type(v) == ffi::SQLITE_TEXT
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl FromValue for 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 len = ffi::sqlite3_value_bytes(v);
|
|
||||||
|
|
||||||
assert!(len >= 0,
|
match ffi::sqlite3_value_type(value) {
|
||||||
"unexpected negative return from sqlite3_value_bytes");
|
ffi::SQLITE_NULL => ValueRef::Null,
|
||||||
let len = len as usize;
|
ffi::SQLITE_INTEGER => ValueRef::Integer(ffi::sqlite3_value_int64(value)),
|
||||||
|
ffi::SQLITE_FLOAT => ValueRef::Real(ffi::sqlite3_value_double(value)),
|
||||||
|
ffi::SQLITE_TEXT => {
|
||||||
|
let text = ffi::sqlite3_value_text(value);
|
||||||
|
assert!(!text.is_null(), "unexpected SQLITE_TEXT value type with NULL data");
|
||||||
|
let s = CStr::from_ptr(text as *const c_char);
|
||||||
|
|
||||||
Ok(from_raw_parts(mem::transmute(c_blob), len).to_vec())
|
// sqlite3_value_text returns UTF8 data, so our unwrap here should be fine.
|
||||||
|
let s = s.to_str().expect("sqlite3_value_text returned invalid UTF-8");
|
||||||
|
ValueRef::Text(s)
|
||||||
}
|
}
|
||||||
|
ffi::SQLITE_BLOB => {
|
||||||
|
let blob = ffi::sqlite3_value_blob(value);
|
||||||
|
assert!(!blob.is_null(), "unexpected SQLITE_BLOB value type with NULL data");
|
||||||
|
|
||||||
unsafe fn parameter_has_valid_sqlite_type(v: *mut sqlite3_value) -> bool {
|
let len = ffi::sqlite3_value_bytes(value);
|
||||||
sqlite3_value_type(v) == ffi::SQLITE_BLOB
|
assert!(len >= 0, "unexpected negative return from sqlite3_value_bytes");
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: FromValue> FromValue for Option<T> {
|
ValueRef::Blob(from_raw_parts(blob as *const u8, len as usize))
|
||||||
unsafe fn parameter_value(v: *mut sqlite3_value) -> Result<Option<T>> {
|
|
||||||
if sqlite3_value_type(v) == ffi::SQLITE_NULL {
|
|
||||||
Ok(None)
|
|
||||||
} else {
|
|
||||||
FromValue::parameter_value(v).map(Some)
|
|
||||||
}
|
}
|
||||||
|
_ => unreachable!("sqlite3_value_type returned invalid value")
|
||||||
}
|
}
|
||||||
|
|
||||||
unsafe fn parameter_has_valid_sqlite_type(v: *mut sqlite3_value) -> bool {
|
|
||||||
sqlite3_value_type(v) == ffi::SQLITE_NULL || T::parameter_has_valid_sqlite_type(v)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -308,15 +234,13 @@ 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) -> Result<T> {
|
pub fn get<T: FromSql>(&self, idx: usize) -> Result<T> {
|
||||||
let arg = self.args[idx];
|
let arg = self.args[idx];
|
||||||
unsafe {
|
let value = unsafe { ValueRef::from_value(arg) };
|
||||||
if T::parameter_has_valid_sqlite_type(arg) {
|
FromSql::column_result(value).map_err(|err| match err {
|
||||||
T::parameter_value(arg)
|
Error::InvalidColumnType => Error::InvalidFunctionParameterType,
|
||||||
} else {
|
_ => err
|
||||||
Err(Error::InvalidFunctionParameterType)
|
})
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sets the auxilliary data associated with a particular parameter. See
|
/// Sets the auxilliary data associated with a particular parameter. See
|
||||||
|
51
src/lib.rs
51
src/lib.rs
@ -75,7 +75,7 @@ use std::result;
|
|||||||
use std::str;
|
use std::str;
|
||||||
use libc::{c_int, c_char};
|
use libc::{c_int, c_char};
|
||||||
|
|
||||||
use types::{ToSql, FromSql};
|
use types::{ToSql, FromSql, ValueRef};
|
||||||
use error::{error_from_sqlite_code, error_from_handle};
|
use error::{error_from_sqlite_code, error_from_handle};
|
||||||
use raw_statement::RawStatement;
|
use raw_statement::RawStatement;
|
||||||
use cache::StatementCache;
|
use cache::StatementCache;
|
||||||
@ -883,7 +883,12 @@ impl<'conn> Statement<'conn> {
|
|||||||
|
|
||||||
for (i, p) in params.iter().enumerate() {
|
for (i, p) in params.iter().enumerate() {
|
||||||
try!(unsafe {
|
try!(unsafe {
|
||||||
self.conn.decode_result(p.bind_parameter(self.stmt.ptr(), (i + 1) as c_int))
|
self.conn.decode_result(
|
||||||
|
// This should be
|
||||||
|
// `p.bind_parameter(self.stmt.ptr(), (i + 1) as c_int)`
|
||||||
|
// but that doesn't compile until Rust 1.9 due to a compiler bug.
|
||||||
|
ToSql::bind_parameter(*p, self.stmt.ptr(), (i + 1) as c_int)
|
||||||
|
)
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1060,14 +1065,9 @@ impl<'a, 'stmt> Row<'a, 'stmt> {
|
|||||||
/// Returns an `Error::InvalidColumnName` if `idx` is not a valid column name
|
/// Returns an `Error::InvalidColumnName` if `idx` is not a valid column name
|
||||||
/// for this row.
|
/// for this row.
|
||||||
pub fn get_checked<I: RowIndex, T: FromSql>(&self, idx: I) -> Result<T> {
|
pub fn get_checked<I: RowIndex, T: FromSql>(&self, idx: I) -> Result<T> {
|
||||||
unsafe {
|
|
||||||
let idx = try!(idx.idx(self.stmt));
|
let idx = try!(idx.idx(self.stmt));
|
||||||
|
let value = unsafe { ValueRef::new(&self.stmt.stmt, idx) };
|
||||||
match T::column_has_valid_sqlite_type(self.stmt.stmt.ptr(), idx) {
|
FromSql::column_result(value)
|
||||||
Ok(()) => FromSql::column_result(self.stmt.stmt.ptr(), idx),
|
|
||||||
Err(e) => Err(e),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Return the number of columns in the current row.
|
/// Return the number of columns in the current row.
|
||||||
@ -1101,6 +1101,39 @@ impl<'a> RowIndex for &'a str {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<'a> ValueRef<'a> {
|
||||||
|
unsafe fn new(stmt: &RawStatement, col: c_int) -> ValueRef {
|
||||||
|
use std::slice::from_raw_parts;
|
||||||
|
|
||||||
|
let raw = stmt.ptr();
|
||||||
|
|
||||||
|
match stmt.column_type(col) {
|
||||||
|
ffi::SQLITE_NULL => ValueRef::Null,
|
||||||
|
ffi::SQLITE_INTEGER => ValueRef::Integer(ffi::sqlite3_column_int64(raw, col)),
|
||||||
|
ffi::SQLITE_FLOAT => ValueRef::Real(ffi::sqlite3_column_double(raw, col)),
|
||||||
|
ffi::SQLITE_TEXT => {
|
||||||
|
let text = ffi::sqlite3_column_text(raw, col);
|
||||||
|
assert!(!text.is_null(), "unexpected SQLITE_TEXT column type with NULL data");
|
||||||
|
let s = CStr::from_ptr(text as *const c_char);
|
||||||
|
|
||||||
|
// sqlite3_column_text returns UTF8 data, so our unwrap here should be fine.
|
||||||
|
let s = s.to_str().expect("sqlite3_column_text returned invalid UTF-8");
|
||||||
|
ValueRef::Text(s)
|
||||||
|
}
|
||||||
|
ffi::SQLITE_BLOB => {
|
||||||
|
let blob = ffi::sqlite3_column_blob(raw, col);
|
||||||
|
assert!(!blob.is_null(), "unexpected SQLITE_BLOB column type with NULL data");
|
||||||
|
|
||||||
|
let len = ffi::sqlite3_column_bytes(raw, col);
|
||||||
|
assert!(len >= 0, "unexpected negative return from sqlite3_column_bytes");
|
||||||
|
|
||||||
|
ValueRef::Blob(from_raw_parts(blob as *const u8, len as usize))
|
||||||
|
}
|
||||||
|
_ => unreachable!("sqlite3_column_type returned invalid value")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod test {
|
||||||
extern crate tempdir;
|
extern crate tempdir;
|
||||||
|
@ -204,7 +204,12 @@ impl<'conn> Statement<'conn> {
|
|||||||
fn bind_parameters_named(&mut self, params: &[(&str, &ToSql)]) -> Result<()> {
|
fn bind_parameters_named(&mut self, params: &[(&str, &ToSql)]) -> Result<()> {
|
||||||
for &(name, value) in params {
|
for &(name, value) in params {
|
||||||
if let Some(i) = try!(self.parameter_index(name)) {
|
if let Some(i) = try!(self.parameter_index(name)) {
|
||||||
try!(self.conn.decode_result(unsafe { value.bind_parameter(self.stmt.ptr(), i) }));
|
try!(self.conn.decode_result(unsafe {
|
||||||
|
// This should be
|
||||||
|
// `value.bind_parameter(self.stmt.ptr(), i)`
|
||||||
|
// but that doesn't compile until Rust 1.9 due to a compiler bug.
|
||||||
|
ToSql::bind_parameter(value, self.stmt.ptr(), i)
|
||||||
|
}));
|
||||||
} else {
|
} else {
|
||||||
return Err(Error::InvalidParameterName(name.into()));
|
return Err(Error::InvalidParameterName(name.into()));
|
||||||
}
|
}
|
||||||
|
@ -20,6 +20,10 @@ impl RawStatement {
|
|||||||
unsafe { ffi::sqlite3_column_count(self.0) }
|
unsafe { ffi::sqlite3_column_count(self.0) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn column_type(&self, idx: c_int) -> c_int {
|
||||||
|
unsafe { ffi::sqlite3_column_type(self.0, idx) }
|
||||||
|
}
|
||||||
|
|
||||||
pub fn column_name(&self, idx: c_int) -> &CStr {
|
pub fn column_name(&self, idx: c_int) -> &CStr {
|
||||||
unsafe { CStr::from_ptr(ffi::sqlite3_column_name(self.0, idx)) }
|
unsafe { CStr::from_ptr(ffi::sqlite3_column_name(self.0, idx)) }
|
||||||
}
|
}
|
||||||
|
@ -1,11 +1,13 @@
|
|||||||
//! Convert most of the [Time Strings](http://sqlite.org/lang_datefunc.html) to chrono types.
|
//! Convert most of the [Time Strings](http://sqlite.org/lang_datefunc.html) to chrono types.
|
||||||
extern crate chrono;
|
extern crate chrono;
|
||||||
|
|
||||||
|
use std::borrow::Cow;
|
||||||
|
|
||||||
use self::chrono::{NaiveDate, NaiveTime, NaiveDateTime, DateTime, TimeZone, UTC, Local};
|
use self::chrono::{NaiveDate, NaiveTime, NaiveDateTime, DateTime, TimeZone, UTC, Local};
|
||||||
use libc::c_int;
|
use libc::c_int;
|
||||||
|
|
||||||
use {Error, Result};
|
use {Error, Result};
|
||||||
use types::{FromSql, ToSql};
|
use types::{FromSql, ToSql, ValueRef};
|
||||||
|
|
||||||
use ffi::sqlite3_stmt;
|
use ffi::sqlite3_stmt;
|
||||||
|
|
||||||
@ -19,16 +21,11 @@ impl ToSql for NaiveDate {
|
|||||||
|
|
||||||
/// "YYYY-MM-DD" => ISO 8601 calendar date without timezone.
|
/// "YYYY-MM-DD" => ISO 8601 calendar date without timezone.
|
||||||
impl FromSql for NaiveDate {
|
impl FromSql for NaiveDate {
|
||||||
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<NaiveDate> {
|
fn column_result(value: ValueRef) -> Result<Self> {
|
||||||
let s = try!(String::column_result(stmt, col));
|
value.as_str().and_then(|s| match NaiveDate::parse_from_str(s, "%Y-%m-%d") {
|
||||||
match NaiveDate::parse_from_str(&s, "%Y-%m-%d") {
|
|
||||||
Ok(dt) => Ok(dt),
|
Ok(dt) => Ok(dt),
|
||||||
Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))),
|
Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))),
|
||||||
}
|
})
|
||||||
}
|
|
||||||
|
|
||||||
unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> Result<()> {
|
|
||||||
String::column_has_valid_sqlite_type(stmt, col)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -42,21 +39,18 @@ impl ToSql for NaiveTime {
|
|||||||
|
|
||||||
/// "HH:MM"/"HH:MM:SS"/"HH:MM:SS.SSS" => ISO 8601 time without timezone.
|
/// "HH:MM"/"HH:MM:SS"/"HH:MM:SS.SSS" => ISO 8601 time without timezone.
|
||||||
impl FromSql for NaiveTime {
|
impl FromSql for NaiveTime {
|
||||||
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<NaiveTime> {
|
fn column_result(value: ValueRef) -> Result<Self> {
|
||||||
let s = try!(String::column_result(stmt, col));
|
value.as_str().and_then(|s| {
|
||||||
let fmt = match s.len() {
|
let fmt = match s.len() {
|
||||||
5 => "%H:%M",
|
5 => "%H:%M",
|
||||||
8 => "%H:%M:%S",
|
8 => "%H:%M:%S",
|
||||||
_ => "%H:%M:%S%.f",
|
_ => "%H:%M:%S%.f",
|
||||||
};
|
};
|
||||||
match NaiveTime::parse_from_str(&s, fmt) {
|
match NaiveTime::parse_from_str(s, fmt) {
|
||||||
Ok(dt) => Ok(dt),
|
Ok(dt) => Ok(dt),
|
||||||
Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))),
|
Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))),
|
||||||
}
|
}
|
||||||
}
|
})
|
||||||
|
|
||||||
unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> Result<()> {
|
|
||||||
String::column_has_valid_sqlite_type(stmt, col)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -71,23 +65,19 @@ impl ToSql for NaiveDateTime {
|
|||||||
/// "YYYY-MM-DD HH:MM:SS"/"YYYY-MM-DD HH:MM:SS.SSS" => ISO 8601 combined date and time
|
/// "YYYY-MM-DD HH:MM:SS"/"YYYY-MM-DD HH:MM:SS.SSS" => ISO 8601 combined date and time
|
||||||
/// without timezone. ("YYYY-MM-DDTHH:MM:SS"/"YYYY-MM-DDTHH:MM:SS.SSS" also supported)
|
/// without timezone. ("YYYY-MM-DDTHH:MM:SS"/"YYYY-MM-DDTHH:MM:SS.SSS" also supported)
|
||||||
impl FromSql for NaiveDateTime {
|
impl FromSql for NaiveDateTime {
|
||||||
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<NaiveDateTime> {
|
fn column_result(value: ValueRef) -> Result<Self> {
|
||||||
let s = try!(String::column_result(stmt, col));
|
value.as_str().and_then(|s| {
|
||||||
|
|
||||||
let fmt = if s.len() >= 11 && s.as_bytes()[10] == b'T' {
|
let fmt = if s.len() >= 11 && s.as_bytes()[10] == b'T' {
|
||||||
"%Y-%m-%dT%H:%M:%S%.f"
|
"%Y-%m-%dT%H:%M:%S%.f"
|
||||||
} else {
|
} else {
|
||||||
"%Y-%m-%d %H:%M:%S%.f"
|
"%Y-%m-%d %H:%M:%S%.f"
|
||||||
};
|
};
|
||||||
|
|
||||||
match NaiveDateTime::parse_from_str(&s, fmt) {
|
match NaiveDateTime::parse_from_str(s, fmt) {
|
||||||
Ok(dt) => Ok(dt),
|
Ok(dt) => Ok(dt),
|
||||||
Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))),
|
Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))),
|
||||||
}
|
}
|
||||||
}
|
})
|
||||||
|
|
||||||
unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> Result<()> {
|
|
||||||
String::column_has_valid_sqlite_type(stmt, col)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -101,38 +91,40 @@ impl<Tz: TimeZone> ToSql for DateTime<Tz> {
|
|||||||
|
|
||||||
/// RFC3339 ("YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM") into DateTime<UTC>.
|
/// RFC3339 ("YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM") into DateTime<UTC>.
|
||||||
impl FromSql for DateTime<UTC> {
|
impl FromSql for DateTime<UTC> {
|
||||||
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<DateTime<UTC>> {
|
fn column_result(value: ValueRef) -> Result<Self> {
|
||||||
let s = {
|
{
|
||||||
let mut s = try!(String::column_result(stmt, col));
|
// Try to parse value as rfc3339 first.
|
||||||
if s.len() >= 11 {
|
let s = try!(value.as_str());
|
||||||
|
|
||||||
|
// If timestamp looks space-separated, make a copy and replace it with 'T'.
|
||||||
|
let s = if s.len() >= 11 && s.as_bytes()[10] == b' ' {
|
||||||
|
let mut s = s.to_string();
|
||||||
|
unsafe {
|
||||||
let sbytes = s.as_mut_vec();
|
let sbytes = s.as_mut_vec();
|
||||||
if sbytes[10] == b' ' {
|
|
||||||
sbytes[10] = b'T';
|
sbytes[10] = b'T';
|
||||||
}
|
}
|
||||||
}
|
Cow::Owned(s)
|
||||||
s
|
} else {
|
||||||
|
Cow::Borrowed(s)
|
||||||
};
|
};
|
||||||
|
|
||||||
match DateTime::parse_from_rfc3339(&s) {
|
match DateTime::parse_from_rfc3339(&s) {
|
||||||
Ok(dt) => Ok(dt.with_timezone(&UTC)),
|
Ok(dt) => return Ok(dt.with_timezone(&UTC)),
|
||||||
Err(_) => NaiveDateTime::column_result(stmt, col).map(|dt| UTC.from_utc_datetime(&dt)),
|
Err(_) => (),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> Result<()> {
|
// Couldn't parse as rfc3339 - fall back to NaiveDateTime.
|
||||||
String::column_has_valid_sqlite_type(stmt, col)
|
NaiveDateTime::column_result(value).map(|dt| UTC.from_utc_datetime(&dt))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RFC3339 ("YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM") into DateTime<Local>.
|
/// RFC3339 ("YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM") into DateTime<Local>.
|
||||||
impl FromSql for DateTime<Local> {
|
impl FromSql for DateTime<Local> {
|
||||||
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<DateTime<Local>> {
|
fn column_result(value: ValueRef) -> Result<Self> {
|
||||||
let utc_dt = try!(DateTime::<UTC>::column_result(stmt, col));
|
let utc_dt = try!(DateTime::<UTC>::column_result(value));
|
||||||
Ok(utc_dt.with_timezone(&Local))
|
Ok(utc_dt.with_timezone(&Local))
|
||||||
}
|
}
|
||||||
|
|
||||||
unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> Result<()> {
|
|
||||||
DateTime::<UTC>::column_has_valid_sqlite_type(stmt, col)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
66
src/types/from_sql.rs
Normal file
66
src/types/from_sql.rs
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
use super::{ValueRef, Value};
|
||||||
|
use ::Result;
|
||||||
|
use ::error::Error;
|
||||||
|
|
||||||
|
/// A trait for types that can be created from a SQLite value.
|
||||||
|
pub trait FromSql: Sized {
|
||||||
|
fn column_result(value: ValueRef) -> Result<Self>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromSql for i32 {
|
||||||
|
fn column_result(value: ValueRef) -> Result<Self> {
|
||||||
|
i64::column_result(value).map(|i| i as i32)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromSql for i64 {
|
||||||
|
fn column_result(value: ValueRef) -> Result<Self> {
|
||||||
|
value.as_i64()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromSql for f64 {
|
||||||
|
fn column_result(value: ValueRef) -> Result<Self> {
|
||||||
|
match value {
|
||||||
|
ValueRef::Integer(i) => Ok(i as f64),
|
||||||
|
ValueRef::Real(f) => Ok(f),
|
||||||
|
_ => Err(Error::InvalidColumnType),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromSql for bool {
|
||||||
|
fn column_result(value: ValueRef) -> Result<Self> {
|
||||||
|
i64::column_result(value).map(|i| match i {
|
||||||
|
0 => false,
|
||||||
|
_ => true,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromSql for String {
|
||||||
|
fn column_result(value: ValueRef) -> Result<Self> {
|
||||||
|
value.as_str().map(|s| s.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromSql for Vec<u8> {
|
||||||
|
fn column_result(value: ValueRef) -> Result<Self> {
|
||||||
|
value.as_blob().map(|b| b.to_vec())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: FromSql> FromSql for Option<T> {
|
||||||
|
fn column_result(value: ValueRef) -> Result<Self> {
|
||||||
|
match value {
|
||||||
|
ValueRef::Null => Ok(None),
|
||||||
|
_ => FromSql::column_result(value).map(Some),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromSql for Value {
|
||||||
|
fn column_result(value: ValueRef) -> Result<Self> {
|
||||||
|
Ok(value.into())
|
||||||
|
}
|
||||||
|
}
|
257
src/types/mod.rs
257
src/types/mod.rs
@ -4,7 +4,9 @@
|
|||||||
//! the `ToSql` and `FromSql` traits are provided for the basic types that SQLite provides methods
|
//! the `ToSql` and `FromSql` traits are provided for the basic types that SQLite provides methods
|
||||||
//! for:
|
//! for:
|
||||||
//!
|
//!
|
||||||
//! * C integers and doubles (`c_int` and `c_double`)
|
//! * Integers (`i32` and `i64`; SQLite uses `i64` internally, so getting an `i32` will truncate
|
||||||
|
//! if the value is too large or too small).
|
||||||
|
//! * Reals (`f64`)
|
||||||
//! * Strings (`String` and `&str`)
|
//! * Strings (`String` and `&str`)
|
||||||
//! * Blobs (`Vec<u8>` and `&[u8]`)
|
//! * Blobs (`Vec<u8>` and `&[u8]`)
|
||||||
//!
|
//!
|
||||||
@ -13,13 +15,7 @@
|
|||||||
//! `"%Y-%m-%d %H:%M:%S"`, as SQLite's builtin
|
//! `"%Y-%m-%d %H:%M:%S"`, as SQLite's builtin
|
||||||
//! [datetime](https://www.sqlite.org/lang_datefunc.html) function. Note that this storage
|
//! [datetime](https://www.sqlite.org/lang_datefunc.html) function. Note that this storage
|
||||||
//! truncates timespecs to the nearest second. If you want different storage for timespecs, you can
|
//! truncates timespecs to the nearest second. If you want different storage for timespecs, you can
|
||||||
//! use a newtype. For example, to store timespecs as doubles:
|
//! use a newtype. For example, to store timespecs as `f64`s:
|
||||||
//!
|
|
||||||
//! `ToSql` and `FromSql` are also implemented for `Option<T>` where `T` implements `ToSql` or
|
|
||||||
//! `FromSql` for the cases where you want to know if a value was NULL (which gets translated to
|
|
||||||
//! `None`). If you get a value that was NULL in SQLite but you store it into a non-`Option` value
|
|
||||||
//! in Rust, you will get a "sensible" zero value - 0 for numeric types (including timespecs), an
|
|
||||||
//! empty string, or an empty vector of bytes.
|
|
||||||
//!
|
//!
|
||||||
//! ```rust,ignore
|
//! ```rust,ignore
|
||||||
//! extern crate rusqlite;
|
//! extern crate rusqlite;
|
||||||
@ -33,10 +29,8 @@
|
|||||||
//! pub struct TimespecSql(pub time::Timespec);
|
//! pub struct TimespecSql(pub time::Timespec);
|
||||||
//!
|
//!
|
||||||
//! impl FromSql for TimespecSql {
|
//! impl FromSql for TimespecSql {
|
||||||
//! unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int)
|
//! fn column_result(value: ValueRef) -> Result<Self> {
|
||||||
//! -> Result<TimespecSql> {
|
//! f64::column_result(value).map(|as_f64| {
|
||||||
//! let as_f64_result = FromSql::column_result(stmt, col);
|
|
||||||
//! as_f64_result.map(|as_f64: f64| {
|
|
||||||
//! TimespecSql(time::Timespec{ sec: as_f64.trunc() as i64,
|
//! TimespecSql(time::Timespec{ sec: as_f64.trunc() as i64,
|
||||||
//! nsec: (as_f64.fract() * 1.0e9) as i32 })
|
//! nsec: (as_f64.fract() * 1.0e9) as i32 })
|
||||||
//! })
|
//! })
|
||||||
@ -51,132 +45,26 @@
|
|||||||
//! }
|
//! }
|
||||||
//! }
|
//! }
|
||||||
//! ```
|
//! ```
|
||||||
|
//!
|
||||||
use libc::{c_int, c_double, c_char};
|
//! `ToSql` and `FromSql` are also implemented for `Option<T>` where `T` implements `ToSql` or
|
||||||
use std::ffi::CStr;
|
//! `FromSql` for the cases where you want to know if a value was NULL (which gets translated to
|
||||||
use std::mem;
|
//! `None`).
|
||||||
use std::str;
|
|
||||||
use super::ffi;
|
|
||||||
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::{SQLITE_INTEGER, SQLITE_FLOAT, SQLITE_TEXT, SQLITE_BLOB, SQLITE_NULL};
|
pub use self::from_sql::FromSql;
|
||||||
|
pub use self::to_sql::ToSql;
|
||||||
|
pub use self::value_ref::ValueRef;
|
||||||
|
|
||||||
|
mod value_ref;
|
||||||
|
mod from_sql;
|
||||||
|
mod to_sql;
|
||||||
mod time;
|
mod time;
|
||||||
#[cfg(feature = "chrono")]
|
#[cfg(feature = "chrono")]
|
||||||
mod chrono;
|
mod chrono;
|
||||||
#[cfg(feature = "serde_json")]
|
#[cfg(feature = "serde_json")]
|
||||||
mod serde_json;
|
mod serde_json;
|
||||||
|
|
||||||
/// A trait for types that can be converted into SQLite values.
|
|
||||||
pub trait ToSql {
|
|
||||||
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A trait for types that can be created from a SQLite value.
|
|
||||||
pub trait FromSql: Sized {
|
|
||||||
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<Self>;
|
|
||||||
|
|
||||||
/// FromSql types can implement this method and use sqlite3_column_type to check that
|
|
||||||
/// the type reported by SQLite matches a type suitable for Self. This method is used
|
|
||||||
/// by `Row::get_checked` to confirm that the column contains a valid type before
|
|
||||||
/// attempting to retrieve the value.
|
|
||||||
unsafe fn column_has_valid_sqlite_type(_: *mut sqlite3_stmt, _: c_int) -> Result<()> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe fn column_has_expected_typed(stmt: *mut sqlite3_stmt,
|
|
||||||
col: c_int,
|
|
||||||
expected_type: c_int)
|
|
||||||
-> Result<()> {
|
|
||||||
let actual_type = sqlite3_column_type(stmt, col);
|
|
||||||
if actual_type == expected_type {
|
|
||||||
Ok(())
|
|
||||||
} else {
|
|
||||||
Err(Error::InvalidColumnType(col, actual_type))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
macro_rules! raw_to_impl(
|
|
||||||
($t:ty, $f:ident) => (
|
|
||||||
impl ToSql for $t {
|
|
||||||
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
|
|
||||||
ffi::$f(stmt, col, *self)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
raw_to_impl!(c_int, sqlite3_bind_int); // i32
|
|
||||||
raw_to_impl!(i64, sqlite3_bind_int64);
|
|
||||||
raw_to_impl!(c_double, sqlite3_bind_double);
|
|
||||||
|
|
||||||
impl ToSql for bool {
|
|
||||||
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
|
|
||||||
if *self {
|
|
||||||
ffi::sqlite3_bind_int(stmt, col, 1)
|
|
||||||
} else {
|
|
||||||
ffi::sqlite3_bind_int(stmt, col, 0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> ToSql for &'a str {
|
|
||||||
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
|
|
||||||
let length = self.len();
|
|
||||||
if length > ::std::i32::MAX as usize {
|
|
||||||
return ffi::SQLITE_TOOBIG;
|
|
||||||
}
|
|
||||||
match str_to_cstring(self) {
|
|
||||||
Ok(c_str) => {
|
|
||||||
ffi::sqlite3_bind_text(stmt,
|
|
||||||
col,
|
|
||||||
c_str.as_ptr(),
|
|
||||||
length as c_int,
|
|
||||||
ffi::SQLITE_TRANSIENT())
|
|
||||||
}
|
|
||||||
Err(_) => ffi::SQLITE_MISUSE,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ToSql for String {
|
|
||||||
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
|
|
||||||
(&self[..]).bind_parameter(stmt, col)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> ToSql for &'a [u8] {
|
|
||||||
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
|
|
||||||
if self.len() > ::std::i32::MAX as usize {
|
|
||||||
return ffi::SQLITE_TOOBIG;
|
|
||||||
}
|
|
||||||
ffi::sqlite3_bind_blob(stmt,
|
|
||||||
col,
|
|
||||||
mem::transmute(self.as_ptr()),
|
|
||||||
self.len() as c_int,
|
|
||||||
ffi::SQLITE_TRANSIENT())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ToSql for Vec<u8> {
|
|
||||||
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
|
|
||||||
(&self[..]).bind_parameter(stmt, col)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: ToSql> ToSql for Option<T> {
|
|
||||||
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
|
|
||||||
match *self {
|
|
||||||
None => ffi::sqlite3_bind_null(stmt, col),
|
|
||||||
Some(ref t) => t.bind_parameter(stmt, col),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Empty struct that can be used to fill in a query parameter as `NULL`.
|
/// Empty struct that can be used to fill in a query parameter as `NULL`.
|
||||||
///
|
///
|
||||||
/// ## Example
|
/// ## Example
|
||||||
@ -196,100 +84,11 @@ impl<T: ToSql> ToSql for Option<T> {
|
|||||||
#[derive(Copy,Clone)]
|
#[derive(Copy,Clone)]
|
||||||
pub struct Null;
|
pub struct Null;
|
||||||
|
|
||||||
impl ToSql for Null {
|
|
||||||
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
|
|
||||||
ffi::sqlite3_bind_null(stmt, col)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
macro_rules! raw_from_impl(
|
/// Owning [dynamic type value](http://sqlite.org/datatype3.html). Value's type is typically
|
||||||
($t:ty, $f:ident, $c:expr) => (
|
/// dictated by SQLite (not by the caller).
|
||||||
impl FromSql for $t {
|
///
|
||||||
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<$t> {
|
/// See [`ValueRef`](enum.ValueRef.html) for a non-owning dynamic type value.
|
||||||
Ok(ffi::$f(stmt, col))
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> Result<()> {
|
|
||||||
column_has_expected_typed(stmt, col, $c)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
raw_from_impl!(c_int, sqlite3_column_int, ffi::SQLITE_INTEGER); // i32
|
|
||||||
raw_from_impl!(i64, sqlite3_column_int64, ffi::SQLITE_INTEGER);
|
|
||||||
raw_from_impl!(c_double, sqlite3_column_double, ffi::SQLITE_FLOAT); // f64
|
|
||||||
|
|
||||||
impl FromSql for bool {
|
|
||||||
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<bool> {
|
|
||||||
match ffi::sqlite3_column_int(stmt, col) {
|
|
||||||
0 => Ok(false),
|
|
||||||
_ => Ok(true),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> Result<()> {
|
|
||||||
column_has_expected_typed(stmt, col, ffi::SQLITE_INTEGER)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl FromSql for String {
|
|
||||||
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<String> {
|
|
||||||
let c_text = ffi::sqlite3_column_text(stmt, col);
|
|
||||||
if c_text.is_null() {
|
|
||||||
Ok("".to_owned())
|
|
||||||
} else {
|
|
||||||
let c_slice = CStr::from_ptr(c_text as *const c_char).to_bytes();
|
|
||||||
let utf8_str = try!(str::from_utf8(c_slice));
|
|
||||||
Ok(utf8_str.into())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> Result<()> {
|
|
||||||
column_has_expected_typed(stmt, col, ffi::SQLITE_TEXT)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl FromSql for Vec<u8> {
|
|
||||||
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<Vec<u8>> {
|
|
||||||
use std::slice::from_raw_parts;
|
|
||||||
let c_blob = ffi::sqlite3_column_blob(stmt, col);
|
|
||||||
let len = ffi::sqlite3_column_bytes(stmt, col);
|
|
||||||
|
|
||||||
// The documentation for sqlite3_column_bytes indicates it is always non-negative,
|
|
||||||
// but we should assert here just to be sure.
|
|
||||||
assert!(len >= 0,
|
|
||||||
"unexpected negative return from sqlite3_column_bytes");
|
|
||||||
let len = len as usize;
|
|
||||||
|
|
||||||
Ok(from_raw_parts(mem::transmute(c_blob), len).to_vec())
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> Result<()> {
|
|
||||||
column_has_expected_typed(stmt, col, ffi::SQLITE_BLOB)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: FromSql> FromSql for 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 {
|
|
||||||
Ok(None)
|
|
||||||
} else {
|
|
||||||
FromSql::column_result(stmt, col).map(Some)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> Result<()> {
|
|
||||||
if sqlite3_column_type(stmt, col) == ffi::SQLITE_NULL {
|
|
||||||
Ok(())
|
|
||||||
} else {
|
|
||||||
T::column_has_valid_sqlite_type(stmt, col)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Dynamic type value (http://sqlite.org/datatype3.html)
|
|
||||||
/// Value's type is dictated by SQLite (not by the caller).
|
|
||||||
#[derive(Clone,Debug,PartialEq)]
|
#[derive(Clone,Debug,PartialEq)]
|
||||||
pub enum Value {
|
pub enum Value {
|
||||||
/// The value is a `NULL` value.
|
/// The value is a `NULL` value.
|
||||||
@ -304,19 +103,6 @@ pub enum Value {
|
|||||||
Blob(Vec<u8>),
|
Blob(Vec<u8>),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FromSql for Value {
|
|
||||||
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<Value> {
|
|
||||||
match sqlite3_column_type(stmt, col) {
|
|
||||||
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_FLOAT => Ok(Value::Real(ffi::sqlite3_column_double(stmt, col))),
|
|
||||||
ffi::SQLITE_NULL => Ok(Value::Null),
|
|
||||||
ffi::SQLITE_BLOB => FromSql::column_result(stmt, col).map(Value::Blob),
|
|
||||||
ct => Err(Error::InvalidColumnType(col, ct)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
#[cfg_attr(feature="clippy", allow(similar_names))]
|
#[cfg_attr(feature="clippy", allow(similar_names))]
|
||||||
mod test {
|
mod test {
|
||||||
@ -434,10 +220,9 @@ mod test {
|
|||||||
assert!(is_invalid_column_type(row.get_checked::<i32, Option<c_int>>(1).err().unwrap()));
|
assert!(is_invalid_column_type(row.get_checked::<i32, Option<c_int>>(1).err().unwrap()));
|
||||||
|
|
||||||
// 2 is actually an integer
|
// 2 is actually an integer
|
||||||
assert!(is_invalid_column_type(row.get_checked::<i32, c_double>(2).err().unwrap()));
|
|
||||||
assert!(is_invalid_column_type(row.get_checked::<i32, String>(2).err().unwrap()));
|
assert!(is_invalid_column_type(row.get_checked::<i32, String>(2).err().unwrap()));
|
||||||
assert!(is_invalid_column_type(row.get_checked::<i32, Vec<u8>>(2).err().unwrap()));
|
assert!(is_invalid_column_type(row.get_checked::<i32, Vec<u8>>(2).err().unwrap()));
|
||||||
assert!(is_invalid_column_type(row.get_checked::<i32, Option<c_double>>(2).err().unwrap()));
|
assert!(is_invalid_column_type(row.get_checked::<i32, Option<String>>(2).err().unwrap()));
|
||||||
|
|
||||||
// 3 is actually a float (c_double)
|
// 3 is actually a float (c_double)
|
||||||
assert!(is_invalid_column_type(row.get_checked::<i32, c_int>(3).err().unwrap()));
|
assert!(is_invalid_column_type(row.get_checked::<i32, c_int>(3).err().unwrap()));
|
||||||
|
@ -5,11 +5,9 @@ use libc::c_int;
|
|||||||
use self::serde_json::Value;
|
use self::serde_json::Value;
|
||||||
|
|
||||||
use {Error, Result};
|
use {Error, Result};
|
||||||
use types::{FromSql, ToSql};
|
use types::{FromSql, ToSql, ValueRef};
|
||||||
|
|
||||||
use ffi;
|
|
||||||
use ffi::sqlite3_stmt;
|
use ffi::sqlite3_stmt;
|
||||||
use ffi::sqlite3_column_type;
|
|
||||||
|
|
||||||
/// Serialize JSON `Value` to text.
|
/// Serialize JSON `Value` to text.
|
||||||
impl ToSql for Value {
|
impl ToSql for Value {
|
||||||
@ -21,19 +19,12 @@ impl ToSql for Value {
|
|||||||
|
|
||||||
/// Deserialize text/blob to JSON `Value`.
|
/// Deserialize text/blob to JSON `Value`.
|
||||||
impl FromSql for Value {
|
impl FromSql for Value {
|
||||||
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<Value> {
|
fn column_result(value: ValueRef) -> Result<Self> {
|
||||||
let value_result = match sqlite3_column_type(stmt, col) {
|
match value {
|
||||||
ffi::SQLITE_TEXT => {
|
ValueRef::Text(ref s) => serde_json::from_str(s),
|
||||||
let s = try!(String::column_result(stmt, col));
|
ValueRef::Blob(ref b) => serde_json::from_slice(b),
|
||||||
serde_json::from_str(&s)
|
_ => return Err(Error::InvalidColumnType),
|
||||||
}
|
}.map_err(|err| Error::FromSqlConversionFailure(Box::new(err)))
|
||||||
ffi::SQLITE_BLOB => {
|
|
||||||
let blob = try!(Vec::<u8>::column_result(stmt, col));
|
|
||||||
serde_json::from_slice(&blob)
|
|
||||||
}
|
|
||||||
ct => return Err(Error::InvalidColumnType(col, ct)),
|
|
||||||
};
|
|
||||||
value_result.map_err(|err| Error::FromSqlConversionFailure(Box::new(err)))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -2,7 +2,7 @@ extern crate time;
|
|||||||
|
|
||||||
use libc::c_int;
|
use libc::c_int;
|
||||||
use {Error, Result};
|
use {Error, Result};
|
||||||
use types::{FromSql, ToSql};
|
use types::{FromSql, ToSql, ValueRef};
|
||||||
|
|
||||||
use ffi::sqlite3_stmt;
|
use ffi::sqlite3_stmt;
|
||||||
|
|
||||||
@ -16,16 +16,11 @@ impl ToSql for time::Timespec {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl FromSql for time::Timespec {
|
impl FromSql for time::Timespec {
|
||||||
unsafe fn column_result(stmt: *mut sqlite3_stmt, col: c_int) -> Result<time::Timespec> {
|
fn column_result(value: ValueRef) -> Result<Self> {
|
||||||
let s = try!(String::column_result(stmt, col));
|
value.as_str().and_then(|s| match time::strptime(s, SQLITE_DATETIME_FMT) {
|
||||||
match time::strptime(&s, SQLITE_DATETIME_FMT) {
|
|
||||||
Ok(tm) => Ok(tm.to_timespec()),
|
Ok(tm) => Ok(tm.to_timespec()),
|
||||||
Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))),
|
Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))),
|
||||||
}
|
})
|
||||||
}
|
|
||||||
|
|
||||||
unsafe fn column_has_valid_sqlite_type(stmt: *mut sqlite3_stmt, col: c_int) -> Result<()> {
|
|
||||||
String::column_has_valid_sqlite_type(stmt, col)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
95
src/types/to_sql.rs
Normal file
95
src/types/to_sql.rs
Normal file
@ -0,0 +1,95 @@
|
|||||||
|
use std::mem;
|
||||||
|
|
||||||
|
use libc::{c_double, c_int};
|
||||||
|
|
||||||
|
use super::Null;
|
||||||
|
use ::{ffi, str_to_cstring};
|
||||||
|
use ffi::sqlite3_stmt;
|
||||||
|
|
||||||
|
/// A trait for types that can be converted into SQLite values.
|
||||||
|
pub trait ToSql {
|
||||||
|
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int;
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! raw_to_impl(
|
||||||
|
($t:ty, $f:ident) => (
|
||||||
|
impl ToSql for $t {
|
||||||
|
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
|
||||||
|
ffi::$f(stmt, col, *self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
raw_to_impl!(c_int, sqlite3_bind_int); // i32
|
||||||
|
raw_to_impl!(i64, sqlite3_bind_int64);
|
||||||
|
raw_to_impl!(c_double, sqlite3_bind_double);
|
||||||
|
|
||||||
|
impl ToSql for bool {
|
||||||
|
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
|
||||||
|
if *self {
|
||||||
|
ffi::sqlite3_bind_int(stmt, col, 1)
|
||||||
|
} else {
|
||||||
|
ffi::sqlite3_bind_int(stmt, col, 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> ToSql for &'a str {
|
||||||
|
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
|
||||||
|
let length = self.len();
|
||||||
|
if length > ::std::i32::MAX as usize {
|
||||||
|
return ffi::SQLITE_TOOBIG;
|
||||||
|
}
|
||||||
|
match str_to_cstring(self) {
|
||||||
|
Ok(c_str) => {
|
||||||
|
ffi::sqlite3_bind_text(stmt,
|
||||||
|
col,
|
||||||
|
c_str.as_ptr(),
|
||||||
|
length as c_int,
|
||||||
|
ffi::SQLITE_TRANSIENT())
|
||||||
|
}
|
||||||
|
Err(_) => ffi::SQLITE_MISUSE,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ToSql for String {
|
||||||
|
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
|
||||||
|
(&self[..]).bind_parameter(stmt, col)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> ToSql for &'a [u8] {
|
||||||
|
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
|
||||||
|
if self.len() > ::std::i32::MAX as usize {
|
||||||
|
return ffi::SQLITE_TOOBIG;
|
||||||
|
}
|
||||||
|
ffi::sqlite3_bind_blob(stmt,
|
||||||
|
col,
|
||||||
|
mem::transmute(self.as_ptr()),
|
||||||
|
self.len() as c_int,
|
||||||
|
ffi::SQLITE_TRANSIENT())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ToSql for Vec<u8> {
|
||||||
|
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
|
||||||
|
(&self[..]).bind_parameter(stmt, col)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ToSql> ToSql for Option<T> {
|
||||||
|
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
|
||||||
|
match *self {
|
||||||
|
None => ffi::sqlite3_bind_null(stmt, col),
|
||||||
|
Some(ref t) => t.bind_parameter(stmt, col),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ToSql for Null {
|
||||||
|
unsafe fn bind_parameter(&self, stmt: *mut sqlite3_stmt, col: c_int) -> c_int {
|
||||||
|
ffi::sqlite3_bind_null(stmt, col)
|
||||||
|
}
|
||||||
|
}
|
83
src/types/value_ref.rs
Normal file
83
src/types/value_ref.rs
Normal file
@ -0,0 +1,83 @@
|
|||||||
|
use ::Result;
|
||||||
|
use ::error::Error;
|
||||||
|
use super::Value;
|
||||||
|
|
||||||
|
/// A non-owning [dynamic type value](http://sqlite.org/datatype3.html). Typically the
|
||||||
|
/// memory backing this value is owned by SQLite.
|
||||||
|
///
|
||||||
|
/// See [`Value`](enum.Value.html) for an owning dynamic type value.
|
||||||
|
#[derive(Copy,Clone,Debug,PartialEq)]
|
||||||
|
pub enum ValueRef<'a> {
|
||||||
|
/// The value is a `NULL` value.
|
||||||
|
Null,
|
||||||
|
/// The value is a signed integer.
|
||||||
|
Integer(i64),
|
||||||
|
/// The value is a floating point number.
|
||||||
|
Real(f64),
|
||||||
|
/// The value is a text string.
|
||||||
|
Text(&'a str),
|
||||||
|
/// The value is a blob of data
|
||||||
|
Blob(&'a [u8]),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> ValueRef<'a> {
|
||||||
|
/// If `self` is case `Integer`, returns the integral value. Otherwise, returns
|
||||||
|
/// `Err(Error::InvalidColumnType)`.
|
||||||
|
pub fn as_i64(&self) -> Result<i64> {
|
||||||
|
match *self {
|
||||||
|
ValueRef::Integer(i) => Ok(i),
|
||||||
|
_ => Err(Error::InvalidColumnType),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// If `self` is case `Real`, returns the floating point value. Otherwise, returns
|
||||||
|
/// `Err(Error::InvalidColumnType)`.
|
||||||
|
pub fn as_f64(&self) -> Result<f64> {
|
||||||
|
match *self {
|
||||||
|
ValueRef::Real(f) => Ok(f),
|
||||||
|
_ => Err(Error::InvalidColumnType),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// If `self` is case `Text`, returns the string value. Otherwise, returns
|
||||||
|
/// `Err(Error::InvalidColumnType)`.
|
||||||
|
pub fn as_str(&self) -> Result<&str> {
|
||||||
|
match *self {
|
||||||
|
ValueRef::Text(ref t) => Ok(t),
|
||||||
|
_ => Err(Error::InvalidColumnType),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// If `self` is case `Blob`, returns the byte slice. Otherwise, returns
|
||||||
|
/// `Err(Error::InvalidColumnType)`.
|
||||||
|
pub fn as_blob(&self) -> Result<&[u8]> {
|
||||||
|
match *self {
|
||||||
|
ValueRef::Blob(ref b) => Ok(b),
|
||||||
|
_ => Err(Error::InvalidColumnType),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> From<ValueRef<'a>> for Value {
|
||||||
|
fn from(borrowed: ValueRef) -> Value {
|
||||||
|
match borrowed {
|
||||||
|
ValueRef::Null => Value::Null,
|
||||||
|
ValueRef::Integer(i) => Value::Integer(i),
|
||||||
|
ValueRef::Real(r) => Value::Real(r),
|
||||||
|
ValueRef::Text(s) => Value::Text(s.to_string()),
|
||||||
|
ValueRef::Blob(b) => Value::Blob(b.to_vec()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> From<&'a Value> for ValueRef<'a> {
|
||||||
|
fn from(value: &'a Value) -> ValueRef<'a> {
|
||||||
|
match *value {
|
||||||
|
Value::Null => ValueRef::Null,
|
||||||
|
Value::Integer(i) => ValueRef::Integer(i),
|
||||||
|
Value::Real(r) => ValueRef::Real(r),
|
||||||
|
Value::Text(ref s) => ValueRef::Text(s),
|
||||||
|
Value::Blob(ref b) => ValueRef::Blob(b),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user