Introduce FromSqlError as specified by John Gallagher

This commit is contained in:
gwenn
2016-06-02 21:03:25 +02:00
parent 91dc30b04d
commit e2cf171192
9 changed files with 100 additions and 61 deletions

View File

@@ -6,8 +6,7 @@ use std::borrow::Cow;
use self::chrono::{NaiveDate, NaiveTime, NaiveDateTime, DateTime, TimeZone, UTC, Local};
use libc::c_int;
use {Error, Result};
use types::{FromSql, ToSql, ValueRef};
use types::{FromSql, FromSqlError, ToSql, ValueRef};
use ffi::sqlite3_stmt;
@@ -21,10 +20,10 @@ impl ToSql for NaiveDate {
/// "YYYY-MM-DD" => ISO 8601 calendar date without timezone.
impl FromSql for NaiveDate {
fn column_result(value: ValueRef) -> Result<Self> {
fn column_result(value: ValueRef) -> Result<Self, FromSqlError> {
value.as_str().and_then(|s| match NaiveDate::parse_from_str(s, "%Y-%m-%d") {
Ok(dt) => Ok(dt),
Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))),
Err(err) => Err(FromSqlError::Other(Box::new(err))),
})
}
}
@@ -39,7 +38,7 @@ impl ToSql for NaiveTime {
/// "HH:MM"/"HH:MM:SS"/"HH:MM:SS.SSS" => ISO 8601 time without timezone.
impl FromSql for NaiveTime {
fn column_result(value: ValueRef) -> Result<Self> {
fn column_result(value: ValueRef) -> Result<Self, FromSqlError> {
value.as_str().and_then(|s| {
let fmt = match s.len() {
5 => "%H:%M",
@@ -48,7 +47,7 @@ impl FromSql for NaiveTime {
};
match NaiveTime::parse_from_str(s, fmt) {
Ok(dt) => Ok(dt),
Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))),
Err(err) => Err(FromSqlError::Other(Box::new(err))),
}
})
}
@@ -65,7 +64,7 @@ impl ToSql for NaiveDateTime {
/// "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)
impl FromSql for NaiveDateTime {
fn column_result(value: ValueRef) -> Result<Self> {
fn column_result(value: ValueRef) -> Result<Self, FromSqlError> {
value.as_str().and_then(|s| {
let fmt = if s.len() >= 11 && s.as_bytes()[10] == b'T' {
"%Y-%m-%dT%H:%M:%S%.f"
@@ -75,7 +74,7 @@ impl FromSql for NaiveDateTime {
match NaiveDateTime::parse_from_str(s, fmt) {
Ok(dt) => Ok(dt),
Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))),
Err(err) => Err(FromSqlError::Other(Box::new(err))),
}
})
}
@@ -91,7 +90,7 @@ impl<Tz: TimeZone> ToSql for DateTime<Tz> {
/// RFC3339 ("YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM") into DateTime<UTC>.
impl FromSql for DateTime<UTC> {
fn column_result(value: ValueRef) -> Result<Self> {
fn column_result(value: ValueRef) -> Result<Self, FromSqlError> {
{
// Try to parse value as rfc3339 first.
let s = try!(value.as_str());
@@ -121,7 +120,7 @@ impl FromSql for DateTime<UTC> {
/// RFC3339 ("YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM") into DateTime<Local>.
impl FromSql for DateTime<Local> {
fn column_result(value: ValueRef) -> Result<Self> {
fn column_result(value: ValueRef) -> Result<Self, FromSqlError> {
let utc_dt = try!(DateTime::<UTC>::column_result(value));
Ok(utc_dt.with_timezone(&Local))
}

View File

@@ -1,36 +1,73 @@
use super::{ValueRef, Value};
use ::Result;
use ::error::Error;
use std::error::Error;
use std::fmt;
/// Enum listing possible errors from `FromSql` trait.
#[derive(Debug)]
pub enum FromSqlError {
/// Error when an SQLite value is requested, but the type of the result cannot be converted to the
/// requested Rust type.
InvalidType,
/// An error case available for implementors of the `FromSql` trait.
Other(Box<Error + Send + Sync>),
}
impl fmt::Display for FromSqlError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
FromSqlError::InvalidType => write!(f, "Invalid type"),
FromSqlError::Other(ref err) => err.fmt(f),
}
}
}
impl Error for FromSqlError {
fn description(&self) -> &str {
match *self {
FromSqlError::InvalidType => "invalid type",
FromSqlError::Other(ref err) => err.description(),
}
}
#[cfg_attr(feature="clippy", allow(match_same_arms))]
fn cause(&self) -> Option<&Error> {
match *self {
FromSqlError::InvalidType => None,
FromSqlError::Other(ref err) => Some(&**err),
}
}
}
/// A trait for types that can be created from a SQLite value.
pub trait FromSql: Sized {
fn column_result(value: ValueRef) -> Result<Self>;
fn column_result(value: ValueRef) -> Result<Self, FromSqlError>;
}
impl FromSql for i32 {
fn column_result(value: ValueRef) -> Result<Self> {
fn column_result(value: ValueRef) -> Result<Self, FromSqlError> {
i64::column_result(value).map(|i| i as i32)
}
}
impl FromSql for i64 {
fn column_result(value: ValueRef) -> Result<Self> {
fn column_result(value: ValueRef) -> Result<Self, FromSqlError> {
value.as_i64()
}
}
impl FromSql for f64 {
fn column_result(value: ValueRef) -> Result<Self> {
fn column_result(value: ValueRef) -> Result<Self, FromSqlError> {
match value {
ValueRef::Integer(i) => Ok(i as f64),
ValueRef::Real(f) => Ok(f),
_ => Err(Error::InvalidType),
_ => Err(FromSqlError::InvalidType),
}
}
}
impl FromSql for bool {
fn column_result(value: ValueRef) -> Result<Self> {
fn column_result(value: ValueRef) -> Result<Self, FromSqlError> {
i64::column_result(value).map(|i| match i {
0 => false,
_ => true,
@@ -39,19 +76,19 @@ impl FromSql for bool {
}
impl FromSql for String {
fn column_result(value: ValueRef) -> Result<Self> {
fn column_result(value: ValueRef) -> Result<Self, FromSqlError> {
value.as_str().map(|s| s.to_string())
}
}
impl FromSql for Vec<u8> {
fn column_result(value: ValueRef) -> Result<Self> {
fn column_result(value: ValueRef) -> Result<Self, FromSqlError> {
value.as_blob().map(|b| b.to_vec())
}
}
impl<T: FromSql> FromSql for Option<T> {
fn column_result(value: ValueRef) -> Result<Self> {
fn column_result(value: ValueRef) -> Result<Self, FromSqlError> {
match value {
ValueRef::Null => Ok(None),
_ => FromSql::column_result(value).map(Some),
@@ -60,7 +97,7 @@ impl<T: FromSql> FromSql for Option<T> {
}
impl FromSql for Value {
fn column_result(value: ValueRef) -> Result<Self> {
fn column_result(value: ValueRef) -> Result<Self, FromSqlError> {
Ok(value.into())
}
}

View File

@@ -52,7 +52,7 @@
pub use ffi::sqlite3_stmt;
pub use self::from_sql::FromSql;
pub use self::from_sql::{FromSql, FromSqlError};
pub use self::to_sql::ToSql;
pub use self::value_ref::ValueRef;

View File

@@ -4,8 +4,7 @@ extern crate serde_json;
use libc::c_int;
use self::serde_json::Value;
use {Error, Result};
use types::{FromSql, ToSql, ValueRef};
use types::{FromSql, FromSqlError, ToSql, ValueRef};
use ffi::sqlite3_stmt;
@@ -19,13 +18,13 @@ impl ToSql for Value {
/// Deserialize text/blob to JSON `Value`.
impl FromSql for Value {
fn column_result(value: ValueRef) -> Result<Self> {
fn column_result(value: ValueRef) -> Result<Self, FromSqlError> {
match value {
ValueRef::Text(ref s) => serde_json::from_str(s),
ValueRef::Blob(ref b) => serde_json::from_slice(b),
_ => return Err(Error::InvalidType),
_ => return Err(FromSqlError::InvalidType),
}
.map_err(|err| Error::FromSqlConversionFailure(Box::new(err)))
.map_err(|err| FromSqlError::Other(Box::new(err)))
}
}

View File

@@ -1,8 +1,7 @@
extern crate time;
use libc::c_int;
use {Error, Result};
use types::{FromSql, ToSql, ValueRef};
use types::{FromSql, FromSqlError, ToSql, ValueRef};
use ffi::sqlite3_stmt;
@@ -16,10 +15,10 @@ impl ToSql for time::Timespec {
}
impl FromSql for time::Timespec {
fn column_result(value: ValueRef) -> Result<Self> {
fn column_result(value: ValueRef) -> Result<Self, FromSqlError> {
value.as_str().and_then(|s| match time::strptime(s, SQLITE_DATETIME_FMT) {
Ok(tm) => Ok(tm.to_timespec()),
Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))),
Err(err) => Err(FromSqlError::Other(Box::new(err))),
})
}
}

View File

@@ -1,5 +1,4 @@
use ::Result;
use ::error::Error;
use ::types::FromSqlError;
use super::{Value, Type};
/// A non-owning [dynamic type value](http://sqlite.org/datatype3.html). Typically the
@@ -35,37 +34,37 @@ impl<'a> ValueRef<'a> {
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> {
pub fn as_i64(&self) -> Result<i64, FromSqlError> {
match *self {
ValueRef::Integer(i) => Ok(i),
_ => Err(Error::InvalidType),
_ => Err(FromSqlError::InvalidType),
}
}
/// If `self` is case `Real`, returns the floating point value. Otherwise, returns
/// `Err(Error::InvalidColumnType)`.
pub fn as_f64(&self) -> Result<f64> {
pub fn as_f64(&self) -> Result<f64, FromSqlError> {
match *self {
ValueRef::Real(f) => Ok(f),
_ => Err(Error::InvalidType),
_ => Err(FromSqlError::InvalidType),
}
}
/// If `self` is case `Text`, returns the string value. Otherwise, returns
/// `Err(Error::InvalidColumnType)`.
pub fn as_str(&self) -> Result<&str> {
pub fn as_str(&self) -> Result<&str, FromSqlError> {
match *self {
ValueRef::Text(ref t) => Ok(t),
_ => Err(Error::InvalidType),
_ => Err(FromSqlError::InvalidType),
}
}
/// If `self` is case `Blob`, returns the byte slice. Otherwise, returns
/// `Err(Error::InvalidColumnType)`.
pub fn as_blob(&self) -> Result<&[u8]> {
pub fn as_blob(&self) -> Result<&[u8], FromSqlError> {
match *self {
ValueRef::Blob(ref b) => Ok(b),
_ => Err(Error::InvalidType),
_ => Err(FromSqlError::InvalidType),
}
}
}