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.
SqliteSingleThreadedMode,
/// An error case available for implementors of the `FromSql` trait.
FromSqlConversionFailure(Box<error::Error + Send + Sync>),
/// Error when the value of a particular column is requested, but it cannot be converted to
/// the requested Rust type.
FromSqlConversionFailure(usize, Type, Box<error::Error + Send + Sync>),
/// Error converting a string to UTF-8.
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
/// that column cannot be converted to the requested Rust type.
InvalidColumnType(i32, Type),
/// Error when an SQLite value is requested, but the type of the result cannot be converted to the
/// requested Rust type.
InvalidType,
InvalidColumnType(c_int, Type),
/// Error when a query that was expected to insert one row did not insert any or insert many.
StatementChangedRows(c_int),
@ -97,7 +94,13 @@ impl fmt::Display for Error {
write!(f,
"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::NulError(ref err) => err.fmt(f),
Error::InvalidParameterName(ref name) => write!(f, "Invalid parameter name: {}", name),
@ -111,7 +114,6 @@ impl fmt::Display for Error {
Error::InvalidColumnType(i, ref t) => {
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::StatementFailedToInsertRow => write!(f, "Statement failed to insert new row"),
@ -133,7 +135,7 @@ impl error::Error for Error {
Error::SqliteSingleThreadedMode => {
"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::InvalidParameterName(_) => "invalid parameter name",
Error::NulError(ref err) => err.description(),
@ -145,7 +147,6 @@ impl error::Error for Error {
Error::InvalidColumnIndex(_) => "invalid column index",
Error::InvalidColumnName(_) => "invalid column name",
Error::InvalidColumnType(_, _) => "invalid column type",
Error::InvalidType => "invalid type",
Error::StatementChangedRows(_) => "query inserted zero or more than one row",
Error::StatementFailedToInsertRow => "statement failed to insert new row",
@ -160,7 +161,7 @@ impl error::Error for Error {
fn cause(&self) -> Option<&error::Error> {
match *self {
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::NulError(ref err) => Some(err),
@ -171,7 +172,6 @@ impl error::Error for Error {
Error::InvalidColumnIndex(_) |
Error::InvalidColumnName(_) |
Error::InvalidColumnType(_, _) |
Error::InvalidType |
Error::InvalidPath(_) |
Error::StatementChangedRows(_) |
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_numeric_type;
use types::{Null, FromSql, ValueRef};
use types::{Null, FromSql, FromSqlError, ValueRef};
use {Result, Error, Connection, str_to_cstring, InnerConnection};
@ -218,8 +218,12 @@ impl<'a> Context<'a> {
let arg = self.args[idx];
let value = unsafe { ValueRef::from_value(arg) };
FromSql::column_result(value).map_err(|err| match err {
Error::InvalidType => Error::InvalidFunctionParameterType(idx, value.data_type()),
_ => err,
FromSqlError::InvalidType => {
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 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 raw_statement::RawStatement;
use cache::StatementCache;
@ -1067,8 +1067,10 @@ impl<'a, 'stmt> Row<'a, 'stmt> {
let idx = try!(idx.idx(self.stmt));
let value = unsafe { ValueRef::new(&self.stmt.stmt, idx) };
FromSql::column_result(value).map_err(|err| match err {
Error::InvalidType => Error::InvalidColumnType(idx, value.data_type()),
_ => err,
FromSqlError::InvalidType => Error::InvalidColumnType(idx, value.data_type()),
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 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),
}
}
}