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

@ -19,8 +19,9 @@ pub enum Error {
/// allow single-threaded use only. /// allow single-threaded use only.
SqliteSingleThreadedMode, SqliteSingleThreadedMode,
/// An error case available for implementors of the `FromSql` trait. /// Error when the value of a particular column is requested, but it cannot be converted to
FromSqlConversionFailure(Box<error::Error + Send + Sync>), /// the requested Rust type.
FromSqlConversionFailure(usize, Type, Box<error::Error + Send + Sync>),
/// Error converting a string to UTF-8. /// Error converting a string to UTF-8.
Utf8Error(str::Utf8Error), Utf8Error(str::Utf8Error),
@ -51,11 +52,7 @@ pub enum Error {
/// Error when the value of a particular column is requested, but the type of the result in /// Error when the value of a particular column is requested, but the type of the result in
/// that column cannot be converted to the requested Rust type. /// that column cannot be converted to the requested Rust type.
InvalidColumnType(i32, Type), InvalidColumnType(c_int, Type),
/// Error when an SQLite value is requested, but the type of the result cannot be converted to the
/// requested Rust type.
InvalidType,
/// Error when a query that was expected to insert one row did not insert any or insert many. /// Error when a query that was expected to insert one row did not insert any or insert many.
StatementChangedRows(c_int), StatementChangedRows(c_int),
@ -97,7 +94,13 @@ impl fmt::Display for Error {
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(i, ref t, ref err) => {
write!(f,
"Conversion error from type {} at index: {}, {}",
t,
i,
err)
}
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),
@ -111,7 +114,6 @@ impl fmt::Display for Error {
Error::InvalidColumnType(i, ref t) => { Error::InvalidColumnType(i, ref t) => {
write!(f, "Invalid column type {} at index: {}", t, i) write!(f, "Invalid column type {} at index: {}", t, i)
} }
Error::InvalidType => write!(f, "Invalid type"),
Error::StatementChangedRows(i) => write!(f, "Query changed {} rows", i), Error::StatementChangedRows(i) => write!(f, "Query changed {} rows", i),
Error::StatementFailedToInsertRow => write!(f, "Statement failed to insert new row"), Error::StatementFailedToInsertRow => write!(f, "Statement failed to insert new row"),
@ -133,7 +135,7 @@ impl error::Error for Error {
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(),
@ -145,7 +147,6 @@ impl error::Error for Error {
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",
Error::InvalidType => "invalid type",
Error::StatementChangedRows(_) => "query inserted zero or more than one row", Error::StatementChangedRows(_) => "query inserted zero or more than one row",
Error::StatementFailedToInsertRow => "statement failed to insert new row", Error::StatementFailedToInsertRow => "statement failed to insert new row",
@ -160,7 +161,7 @@ impl error::Error for Error {
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::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),
@ -171,7 +172,6 @@ impl error::Error for Error {
Error::InvalidColumnIndex(_) | Error::InvalidColumnIndex(_) |
Error::InvalidColumnName(_) | Error::InvalidColumnName(_) |
Error::InvalidColumnType(_, _) | Error::InvalidColumnType(_, _) |
Error::InvalidType |
Error::InvalidPath(_) | Error::InvalidPath(_) |
Error::StatementChangedRows(_) | Error::StatementChangedRows(_) |
Error::StatementFailedToInsertRow => None, Error::StatementFailedToInsertRow => None,

View File

@ -62,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, FromSql, ValueRef}; use types::{Null, FromSql, FromSqlError, ValueRef};
use {Result, Error, Connection, str_to_cstring, InnerConnection}; use {Result, Error, Connection, str_to_cstring, InnerConnection};
@ -218,8 +218,12 @@ impl<'a> Context<'a> {
let arg = self.args[idx]; let arg = self.args[idx];
let value = unsafe { ValueRef::from_value(arg) }; let value = unsafe { ValueRef::from_value(arg) };
FromSql::column_result(value).map_err(|err| match err { FromSql::column_result(value).map_err(|err| match err {
Error::InvalidType => Error::InvalidFunctionParameterType(idx, value.data_type()), FromSqlError::InvalidType => {
_ => err, Error::InvalidFunctionParameterType(idx, value.data_type())
}
FromSqlError::Other(err) => {
Error::FromSqlConversionFailure(idx, value.data_type(), err)
}
}) })
} }

View File

@ -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, ValueRef}; use types::{ToSql, FromSql, FromSqlError, 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;
@ -1067,8 +1067,10 @@ impl<'a, 'stmt> Row<'a, 'stmt> {
let idx = try!(idx.idx(self.stmt)); let idx = try!(idx.idx(self.stmt));
let value = unsafe { ValueRef::new(&self.stmt.stmt, idx) }; let value = unsafe { ValueRef::new(&self.stmt.stmt, idx) };
FromSql::column_result(value).map_err(|err| match err { FromSql::column_result(value).map_err(|err| match err {
Error::InvalidType => Error::InvalidColumnType(idx, value.data_type()), FromSqlError::InvalidType => Error::InvalidColumnType(idx, value.data_type()),
_ => err, FromSqlError::Other(err) => {
Error::FromSqlConversionFailure(idx as usize, value.data_type(), err)
}
}) })
} }

View File

@ -6,8 +6,7 @@ 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 types::{FromSql, FromSqlError, ToSql, ValueRef};
use types::{FromSql, ToSql, ValueRef};
use ffi::sqlite3_stmt; use ffi::sqlite3_stmt;
@ -21,10 +20,10 @@ 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 {
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") { value.as_str().and_then(|s| 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(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. /// "HH:MM"/"HH:MM:SS"/"HH:MM:SS.SSS" => ISO 8601 time without timezone.
impl FromSql for NaiveTime { 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| { value.as_str().and_then(|s| {
let fmt = match s.len() { let fmt = match s.len() {
5 => "%H:%M", 5 => "%H:%M",
@ -48,7 +47,7 @@ impl FromSql for NaiveTime {
}; };
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(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 /// "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 {
fn column_result(value: ValueRef) -> Result<Self> { fn column_result(value: ValueRef) -> Result<Self, FromSqlError> {
value.as_str().and_then(|s| { 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"
@ -75,7 +74,7 @@ impl FromSql for NaiveDateTime {
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(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>. /// RFC3339 ("YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM") into DateTime<UTC>.
impl FromSql for 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. // Try to parse value as rfc3339 first.
let s = try!(value.as_str()); 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>. /// RFC3339 ("YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM") into DateTime<Local>.
impl FromSql for DateTime<Local> { impl FromSql for DateTime<Local> {
fn column_result(value: ValueRef) -> Result<Self> { fn column_result(value: ValueRef) -> Result<Self, FromSqlError> {
let utc_dt = try!(DateTime::<UTC>::column_result(value)); let utc_dt = try!(DateTime::<UTC>::column_result(value));
Ok(utc_dt.with_timezone(&Local)) Ok(utc_dt.with_timezone(&Local))
} }

View File

@ -1,36 +1,73 @@
use super::{ValueRef, Value}; use super::{ValueRef, Value};
use ::Result; use std::error::Error;
use ::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. /// A trait for types that can be created from a SQLite value.
pub trait FromSql: Sized { pub trait FromSql: Sized {
fn column_result(value: ValueRef) -> Result<Self>; fn column_result(value: ValueRef) -> Result<Self, FromSqlError>;
} }
impl FromSql for i32 { 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) i64::column_result(value).map(|i| i as i32)
} }
} }
impl FromSql for i64 { impl FromSql for i64 {
fn column_result(value: ValueRef) -> Result<Self> { fn column_result(value: ValueRef) -> Result<Self, FromSqlError> {
value.as_i64() value.as_i64()
} }
} }
impl FromSql for f64 { impl FromSql for f64 {
fn column_result(value: ValueRef) -> Result<Self> { fn column_result(value: ValueRef) -> Result<Self, FromSqlError> {
match value { match value {
ValueRef::Integer(i) => Ok(i as f64), ValueRef::Integer(i) => Ok(i as f64),
ValueRef::Real(f) => Ok(f), ValueRef::Real(f) => Ok(f),
_ => Err(Error::InvalidType), _ => Err(FromSqlError::InvalidType),
} }
} }
} }
impl FromSql for bool { 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 { i64::column_result(value).map(|i| match i {
0 => false, 0 => false,
_ => true, _ => true,
@ -39,19 +76,19 @@ impl FromSql for bool {
} }
impl FromSql for String { 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()) value.as_str().map(|s| s.to_string())
} }
} }
impl FromSql for Vec<u8> { 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()) value.as_blob().map(|b| b.to_vec())
} }
} }
impl<T: FromSql> FromSql for Option<T> { impl<T: FromSql> FromSql for Option<T> {
fn column_result(value: ValueRef) -> Result<Self> { fn column_result(value: ValueRef) -> Result<Self, FromSqlError> {
match value { match value {
ValueRef::Null => Ok(None), ValueRef::Null => Ok(None),
_ => FromSql::column_result(value).map(Some), _ => FromSql::column_result(value).map(Some),
@ -60,7 +97,7 @@ impl<T: FromSql> FromSql for Option<T> {
} }
impl FromSql for Value { impl FromSql for Value {
fn column_result(value: ValueRef) -> Result<Self> { fn column_result(value: ValueRef) -> Result<Self, FromSqlError> {
Ok(value.into()) Ok(value.into())
} }
} }

View File

@ -52,7 +52,7 @@
pub use ffi::sqlite3_stmt; 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::to_sql::ToSql;
pub use self::value_ref::ValueRef; pub use self::value_ref::ValueRef;

View File

@ -4,8 +4,7 @@ extern crate serde_json;
use libc::c_int; use libc::c_int;
use self::serde_json::Value; use self::serde_json::Value;
use {Error, Result}; use types::{FromSql, FromSqlError, ToSql, ValueRef};
use types::{FromSql, ToSql, ValueRef};
use ffi::sqlite3_stmt; use ffi::sqlite3_stmt;
@ -19,13 +18,13 @@ impl ToSql for Value {
/// Deserialize text/blob to JSON `Value`. /// Deserialize text/blob to JSON `Value`.
impl FromSql for Value { impl FromSql for Value {
fn column_result(value: ValueRef) -> Result<Self> { fn column_result(value: ValueRef) -> Result<Self, FromSqlError> {
match value { match value {
ValueRef::Text(ref s) => serde_json::from_str(s), ValueRef::Text(ref s) => serde_json::from_str(s),
ValueRef::Blob(ref b) => serde_json::from_slice(b), 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; extern crate time;
use libc::c_int; use libc::c_int;
use {Error, Result}; use types::{FromSql, FromSqlError, ToSql, ValueRef};
use types::{FromSql, ToSql, ValueRef};
use ffi::sqlite3_stmt; use ffi::sqlite3_stmt;
@ -16,10 +15,10 @@ impl ToSql for time::Timespec {
} }
impl FromSql 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) { value.as_str().and_then(|s| 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(FromSqlError::Other(Box::new(err))),
}) })
} }
} }

View File

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