From cabcaf3dcb31a1f4d76534cc6dc3db933d4c9531 Mon Sep 17 00:00:00 2001 From: gwenn Date: Thu, 26 May 2016 21:03:05 +0200 Subject: [PATCH 1/6] Better error reporting on invalid column type. --- src/error.rs | 21 +++++++++++++-------- src/functions.rs | 8 ++++---- src/lib.rs | 19 +++++++++++-------- src/types/chrono.rs | 22 +++++++++++----------- src/types/from_sql.rs | 32 ++++++++++++++++---------------- src/types/mod.rs | 37 ++++++++++++++++++++++++++++++++++++- src/types/serde_json.rs | 11 ++++++----- src/types/time.rs | 4 ++-- src/types/value_ref.rs | 30 +++++++++++++++++++++--------- 9 files changed, 120 insertions(+), 64 deletions(-) diff --git a/src/error.rs b/src/error.rs index 1d6ccd4..03624d2 100644 --- a/src/error.rs +++ b/src/error.rs @@ -4,6 +4,7 @@ use std::path::PathBuf; use std::str; use libc::c_int; use {ffi, errmsg_to_string}; +use types::Type; /// Old name for `Error`. `SqliteError` is deprecated. pub type SqliteError = Error; @@ -50,7 +51,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, + InvalidColumnType(i32, Type), /// Error when a query that was expected to insert one row did not insert any or insert many. StatementChangedRows(c_int), @@ -62,7 +63,7 @@ pub enum Error { /// Error returned by `functions::Context::get` when the function argument cannot be converted /// to the requested type. #[cfg(feature = "functions")] - InvalidFunctionParameterType, + InvalidFunctionParameterType(i32, Type), /// An error case available for implementors of custom user functions (e.g., /// `create_scalar_function`). @@ -103,12 +104,16 @@ impl fmt::Display for Error { Error::QueryReturnedNoRows => write!(f, "Query returned no rows"), Error::InvalidColumnIndex(i) => write!(f, "Invalid column index: {}", i), Error::InvalidColumnName(ref name) => write!(f, "Invalid column name: {}", name), - Error::InvalidColumnType => write!(f, "Invalid column type"), + Error::InvalidColumnType(i, ref t) => { + write!(f, "Invalid column type {} at index: {}", t, i) + } Error::StatementChangedRows(i) => write!(f, "Query changed {} rows", i), Error::StatementFailedToInsertRow => write!(f, "Statement failed to insert new row"), #[cfg(feature = "functions")] - Error::InvalidFunctionParameterType => write!(f, "Invalid function parameter type"), + Error::InvalidFunctionParameterType(i, ref t) => { + write!(f, "Invalid function parameter type {} at index {}", t, i) + } #[cfg(feature = "functions")] Error::UserFunctionError(ref err) => err.fmt(f), } @@ -134,12 +139,12 @@ impl error::Error for Error { Error::QueryReturnedNoRows => "query returned no rows", Error::InvalidColumnIndex(_) => "invalid column index", Error::InvalidColumnName(_) => "invalid column name", - Error::InvalidColumnType => "invalid column type", + Error::InvalidColumnType(_, _) => "invalid column type", Error::StatementChangedRows(_) => "query inserted zero or more than one row", Error::StatementFailedToInsertRow => "statement failed to insert new row", #[cfg(feature = "functions")] - Error::InvalidFunctionParameterType => "invalid function parameter type", + Error::InvalidFunctionParameterType(_, _) => "invalid function parameter type", #[cfg(feature = "functions")] Error::UserFunctionError(ref err) => err.description(), } @@ -159,13 +164,13 @@ impl error::Error for Error { Error::QueryReturnedNoRows | Error::InvalidColumnIndex(_) | Error::InvalidColumnName(_) | - Error::InvalidColumnType | + Error::InvalidColumnType(_, _) | Error::InvalidPath(_) | Error::StatementChangedRows(_) | Error::StatementFailedToInsertRow => None, #[cfg(feature = "functions")] - Error::InvalidFunctionParameterType => None, + Error::InvalidFunctionParameterType(_, _) => None, #[cfg(feature = "functions")] Error::UserFunctionError(ref err) => Some(&**err), diff --git a/src/functions.rs b/src/functions.rs index 32e4d1e..42fbd78 100644 --- a/src/functions.rs +++ b/src/functions.rs @@ -182,7 +182,7 @@ impl<'a> ValueRef<'a> { ValueRef::Blob(from_raw_parts(blob as *const u8, len as usize)) } - _ => unreachable!("sqlite3_value_type returned invalid value") + _ => unreachable!("sqlite3_value_type returned invalid value"), } } } @@ -217,9 +217,9 @@ impl<'a> Context<'a> { pub fn get(&self, idx: usize) -> Result { let arg = self.args[idx]; let value = unsafe { ValueRef::from_value(arg) }; - FromSql::column_result(value).map_err(|err| match err { - Error::InvalidColumnType => Error::InvalidFunctionParameterType, - _ => err + FromSql::column_result(value, idx as i32).map_err(|err| match err { + Error::InvalidColumnType(i, t) => Error::InvalidFunctionParameterType(i, t), + _ => err, }) } diff --git a/src/lib.rs b/src/lib.rs index 8d84890..0114285 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1066,7 +1066,7 @@ impl<'a, 'stmt> Row<'a, 'stmt> { pub fn get_checked(&self, idx: I) -> Result { let idx = try!(idx.idx(self.stmt)); let value = unsafe { ValueRef::new(&self.stmt.stmt, idx) }; - FromSql::column_result(value) + FromSql::column_result(value, idx) } /// Return the number of columns in the current row. @@ -1112,7 +1112,8 @@ impl<'a> ValueRef<'a> { 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"); + 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. @@ -1121,14 +1122,16 @@ impl<'a> ValueRef<'a> { } ffi::SQLITE_BLOB => { let blob = ffi::sqlite3_column_blob(raw, col); - assert!(!blob.is_null(), "unexpected SQLITE_BLOB column type with NULL data"); + 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"); + 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") + _ => unreachable!("sqlite3_column_type returned invalid value"), } } } @@ -1488,7 +1491,7 @@ mod test { .collect(); match bad_type.unwrap_err() { - Error::InvalidColumnType => (), + Error::InvalidColumnType(_, _) => (), err => panic!("Unexpected error {}", err), } @@ -1548,7 +1551,7 @@ mod test { .collect(); match bad_type.unwrap_err() { - CustomError::Sqlite(Error::InvalidColumnType) => (), + CustomError::Sqlite(Error::InvalidColumnType(_, _)) => (), err => panic!("Unexpected error {}", err), } @@ -1610,7 +1613,7 @@ mod test { }); match bad_type.unwrap_err() { - CustomError::Sqlite(Error::InvalidColumnType) => (), + CustomError::Sqlite(Error::InvalidColumnType(_, _)) => (), err => panic!("Unexpected error {}", err), } diff --git a/src/types/chrono.rs b/src/types/chrono.rs index 3d17dd6..f415a7b 100644 --- a/src/types/chrono.rs +++ b/src/types/chrono.rs @@ -21,8 +21,8 @@ impl ToSql for NaiveDate { /// "YYYY-MM-DD" => ISO 8601 calendar date without timezone. impl FromSql for NaiveDate { - fn column_result(value: ValueRef) -> Result { - value.as_str().and_then(|s| match NaiveDate::parse_from_str(s, "%Y-%m-%d") { + fn column_result(value: ValueRef, idx: i32) -> Result { + value.as_str(idx).and_then(|s| match NaiveDate::parse_from_str(s, "%Y-%m-%d") { Ok(dt) => Ok(dt), Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))), }) @@ -39,8 +39,8 @@ 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 { - value.as_str().and_then(|s| { + fn column_result(value: ValueRef, idx: i32) -> Result { + value.as_str(idx).and_then(|s| { let fmt = match s.len() { 5 => "%H:%M", 8 => "%H:%M:%S", @@ -65,8 +65,8 @@ 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 { - value.as_str().and_then(|s| { + fn column_result(value: ValueRef, idx: i32) -> Result { + value.as_str(idx).and_then(|s| { let fmt = if s.len() >= 11 && s.as_bytes()[10] == b'T' { "%Y-%m-%dT%H:%M:%S%.f" } else { @@ -91,10 +91,10 @@ impl ToSql for DateTime { /// RFC3339 ("YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM") into DateTime. impl FromSql for DateTime { - fn column_result(value: ValueRef) -> Result { + fn column_result(value: ValueRef, idx: i32) -> Result { { // Try to parse value as rfc3339 first. - let s = try!(value.as_str()); + let s = try!(value.as_str(idx)); // If timestamp looks space-separated, make a copy and replace it with 'T'. let s = if s.len() >= 11 && s.as_bytes()[10] == b' ' { @@ -115,14 +115,14 @@ impl FromSql for DateTime { } // Couldn't parse as rfc3339 - fall back to NaiveDateTime. - NaiveDateTime::column_result(value).map(|dt| UTC.from_utc_datetime(&dt)) + NaiveDateTime::column_result(value, idx).map(|dt| UTC.from_utc_datetime(&dt)) } } /// RFC3339 ("YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM") into DateTime. impl FromSql for DateTime { - fn column_result(value: ValueRef) -> Result { - let utc_dt = try!(DateTime::::column_result(value)); + fn column_result(value: ValueRef, idx: i32) -> Result { + let utc_dt = try!(DateTime::::column_result(value, idx)); Ok(utc_dt.with_timezone(&Local)) } } diff --git a/src/types/from_sql.rs b/src/types/from_sql.rs index 28df415..09471e2 100644 --- a/src/types/from_sql.rs +++ b/src/types/from_sql.rs @@ -4,34 +4,34 @@ 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; + fn column_result(value: ValueRef, idx: i32) -> Result; } impl FromSql for i32 { - fn column_result(value: ValueRef) -> Result { - i64::column_result(value).map(|i| i as i32) + fn column_result(value: ValueRef, idx: i32) -> Result { + i64::column_result(value, idx).map(|i| i as i32) } } impl FromSql for i64 { - fn column_result(value: ValueRef) -> Result { - value.as_i64() + fn column_result(value: ValueRef, idx: i32) -> Result { + value.as_i64(idx) } } impl FromSql for f64 { - fn column_result(value: ValueRef) -> Result { + fn column_result(value: ValueRef, idx: i32) -> Result { match value { ValueRef::Integer(i) => Ok(i as f64), ValueRef::Real(f) => Ok(f), - _ => Err(Error::InvalidColumnType), + _ => Err(Error::InvalidColumnType(idx, value.data_type())), } } } impl FromSql for bool { - fn column_result(value: ValueRef) -> Result { - i64::column_result(value).map(|i| match i { + fn column_result(value: ValueRef, idx: i32) -> Result { + i64::column_result(value, idx).map(|i| match i { 0 => false, _ => true, }) @@ -39,28 +39,28 @@ impl FromSql for bool { } impl FromSql for String { - fn column_result(value: ValueRef) -> Result { - value.as_str().map(|s| s.to_string()) + fn column_result(value: ValueRef, idx: i32) -> Result { + value.as_str(idx).map(|s| s.to_string()) } } impl FromSql for Vec { - fn column_result(value: ValueRef) -> Result { - value.as_blob().map(|b| b.to_vec()) + fn column_result(value: ValueRef, idx: i32) -> Result { + value.as_blob(idx).map(|b| b.to_vec()) } } impl FromSql for Option { - fn column_result(value: ValueRef) -> Result { + fn column_result(value: ValueRef, idx: i32) -> Result { match value { ValueRef::Null => Ok(None), - _ => FromSql::column_result(value).map(Some), + _ => FromSql::column_result(value, idx).map(Some), } } } impl FromSql for Value { - fn column_result(value: ValueRef) -> Result { + fn column_result(value: ValueRef, _: i32) -> Result { Ok(value.into()) } } diff --git a/src/types/mod.rs b/src/types/mod.rs index 758eb5d..53b7b9a 100644 --- a/src/types/mod.rs +++ b/src/types/mod.rs @@ -56,6 +56,8 @@ pub use self::from_sql::FromSql; pub use self::to_sql::ToSql; pub use self::value_ref::ValueRef; +use std::fmt; + mod value_ref; mod from_sql; mod to_sql; @@ -102,6 +104,39 @@ pub enum Value { Blob(Vec), } +impl Value { + pub fn data_type(&self) -> Type { + match *self { + Value::Null => Type::Null, + Value::Integer(_) => Type::Integer, + Value::Real(_) => Type::Real, + Value::Text(_) => Type::Text, + Value::Blob(_) => Type::Blob, + } + } +} + +#[derive(Clone,Debug,PartialEq)] +pub enum Type { + Null, + Integer, + Real, + Text, + Blob, +} + +impl fmt::Display for Type { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Type::Null => write!(f, "Null"), + Type::Integer => write!(f, "Integer"), + Type::Real => write!(f, "Real"), + Type::Text => write!(f, "Text"), + Type::Blob => write!(f, "Blob"), + } + } +} + #[cfg(test)] #[cfg_attr(feature="clippy", allow(similar_names))] mod test { @@ -175,7 +210,7 @@ mod test { fn test_mismatched_types() { fn is_invalid_column_type(err: Error) -> bool { match err { - Error::InvalidColumnType => true, + Error::InvalidColumnType(_, _) => true, _ => false, } } diff --git a/src/types/serde_json.rs b/src/types/serde_json.rs index 937f914..4c01f20 100644 --- a/src/types/serde_json.rs +++ b/src/types/serde_json.rs @@ -19,12 +19,13 @@ impl ToSql for Value { /// Deserialize text/blob to JSON `Value`. impl FromSql for Value { - fn column_result(value: ValueRef) -> Result { + fn column_result(value: ValueRef, idx: i32) -> Result { match value { - ValueRef::Text(ref s) => serde_json::from_str(s), - ValueRef::Blob(ref b) => serde_json::from_slice(b), - _ => return Err(Error::InvalidColumnType), - }.map_err(|err| Error::FromSqlConversionFailure(Box::new(err))) + ValueRef::Text(ref s) => serde_json::from_str(s), + ValueRef::Blob(ref b) => serde_json::from_slice(b), + _ => return Err(Error::InvalidColumnType(idx, value.data_type())), + } + .map_err(|err| Error::FromSqlConversionFailure(Box::new(err))) } } diff --git a/src/types/time.rs b/src/types/time.rs index 1f1a818..05dc1b1 100644 --- a/src/types/time.rs +++ b/src/types/time.rs @@ -16,8 +16,8 @@ impl ToSql for time::Timespec { } impl FromSql for time::Timespec { - fn column_result(value: ValueRef) -> Result { - value.as_str().and_then(|s| match time::strptime(s, SQLITE_DATETIME_FMT) { + fn column_result(value: ValueRef, idx: i32) -> Result { + value.as_str(idx).and_then(|s| match time::strptime(s, SQLITE_DATETIME_FMT) { Ok(tm) => Ok(tm.to_timespec()), Err(err) => Err(Error::FromSqlConversionFailure(Box::new(err))), }) diff --git a/src/types/value_ref.rs b/src/types/value_ref.rs index aa2d3b8..01ae8e0 100644 --- a/src/types/value_ref.rs +++ b/src/types/value_ref.rs @@ -1,6 +1,6 @@ use ::Result; use ::error::Error; -use super::Value; +use super::{Value, Type}; /// A non-owning [dynamic type value](http://sqlite.org/datatype3.html). Typically the /// memory backing this value is owned by SQLite. @@ -20,40 +20,52 @@ pub enum ValueRef<'a> { Blob(&'a [u8]), } +impl<'a> ValueRef<'a> { + pub fn data_type(&self) -> Type { + match *self { + ValueRef::Null => Type::Null, + ValueRef::Integer(_) => Type::Integer, + ValueRef::Real(_) => Type::Real, + ValueRef::Text(_) => Type::Text, + ValueRef::Blob(_) => Type::Blob, + } + } +} + impl<'a> ValueRef<'a> { /// If `self` is case `Integer`, returns the integral value. Otherwise, returns /// `Err(Error::InvalidColumnType)`. - pub fn as_i64(&self) -> Result { + pub fn as_i64(&self, idx: i32) -> Result { match *self { ValueRef::Integer(i) => Ok(i), - _ => Err(Error::InvalidColumnType), + _ => Err(Error::InvalidColumnType(idx, self.data_type())), } } /// If `self` is case `Real`, returns the floating point value. Otherwise, returns /// `Err(Error::InvalidColumnType)`. - pub fn as_f64(&self) -> Result { + pub fn as_f64(&self, idx: i32) -> Result { match *self { ValueRef::Real(f) => Ok(f), - _ => Err(Error::InvalidColumnType), + _ => Err(Error::InvalidColumnType(idx, self.data_type())), } } /// 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, idx: i32) -> Result<&str> { match *self { ValueRef::Text(ref t) => Ok(t), - _ => Err(Error::InvalidColumnType), + _ => Err(Error::InvalidColumnType(idx, self.data_type())), } } /// 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, idx: i32) -> Result<&[u8]> { match *self { ValueRef::Blob(ref b) => Ok(b), - _ => Err(Error::InvalidColumnType), + _ => Err(Error::InvalidColumnType(idx, self.data_type())), } } } From fb19e718cfb7742e1791a1073ee39c2621577263 Mon Sep 17 00:00:00 2001 From: gwenn Date: Mon, 30 May 2016 20:35:56 +0200 Subject: [PATCH 2/6] Introduce an intermediary InvalidType error. InvalidType is used where the column/parameter index is not known. --- src/error.rs | 11 ++++++++++- src/functions.rs | 4 ++-- src/lib.rs | 5 ++++- src/types/chrono.rs | 22 +++++++++++----------- src/types/from_sql.rs | 32 ++++++++++++++++---------------- src/types/serde_json.rs | 4 ++-- src/types/time.rs | 4 ++-- src/types/value_ref.rs | 16 ++++++++-------- 8 files changed, 55 insertions(+), 43 deletions(-) diff --git a/src/error.rs b/src/error.rs index 03624d2..f480a42 100644 --- a/src/error.rs +++ b/src/error.rs @@ -53,6 +53,10 @@ pub enum Error { /// 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(Type), + /// Error when a query that was expected to insert one row did not insert any or insert many. StatementChangedRows(c_int), @@ -63,7 +67,7 @@ pub enum Error { /// Error returned by `functions::Context::get` when the function argument cannot be converted /// to the requested type. #[cfg(feature = "functions")] - InvalidFunctionParameterType(i32, Type), + InvalidFunctionParameterType(usize, Type), /// An error case available for implementors of custom user functions (e.g., /// `create_scalar_function`). @@ -107,6 +111,9 @@ impl fmt::Display for Error { Error::InvalidColumnType(i, ref t) => { write!(f, "Invalid column type {} at index: {}", t, i) } + Error::InvalidType(ref t) => { + write!(f, "Invalid type {}", t) + } Error::StatementChangedRows(i) => write!(f, "Query changed {} rows", i), Error::StatementFailedToInsertRow => write!(f, "Statement failed to insert new row"), @@ -140,6 +147,7 @@ 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", @@ -165,6 +173,7 @@ impl error::Error for Error { Error::InvalidColumnIndex(_) | Error::InvalidColumnName(_) | Error::InvalidColumnType(_, _) | + Error::InvalidType(_) | Error::InvalidPath(_) | Error::StatementChangedRows(_) | Error::StatementFailedToInsertRow => None, diff --git a/src/functions.rs b/src/functions.rs index 42fbd78..8065e1a 100644 --- a/src/functions.rs +++ b/src/functions.rs @@ -217,8 +217,8 @@ impl<'a> Context<'a> { pub fn get(&self, idx: usize) -> Result { let arg = self.args[idx]; let value = unsafe { ValueRef::from_value(arg) }; - FromSql::column_result(value, idx as i32).map_err(|err| match err { - Error::InvalidColumnType(i, t) => Error::InvalidFunctionParameterType(i, t), + FromSql::column_result(value).map_err(|err| match err { + Error::InvalidType(t) => Error::InvalidFunctionParameterType(idx, t), _ => err, }) } diff --git a/src/lib.rs b/src/lib.rs index 0114285..72e9a1f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1066,7 +1066,10 @@ impl<'a, 'stmt> Row<'a, 'stmt> { pub fn get_checked(&self, idx: I) -> Result { let idx = try!(idx.idx(self.stmt)); let value = unsafe { ValueRef::new(&self.stmt.stmt, idx) }; - FromSql::column_result(value, idx) + FromSql::column_result(value).map_err(|err| match err { + Error::InvalidType(t) => Error::InvalidColumnType(idx, t), + _ => err, + }) } /// Return the number of columns in the current row. diff --git a/src/types/chrono.rs b/src/types/chrono.rs index f415a7b..3d17dd6 100644 --- a/src/types/chrono.rs +++ b/src/types/chrono.rs @@ -21,8 +21,8 @@ impl ToSql for NaiveDate { /// "YYYY-MM-DD" => ISO 8601 calendar date without timezone. impl FromSql for NaiveDate { - fn column_result(value: ValueRef, idx: i32) -> Result { - value.as_str(idx).and_then(|s| match NaiveDate::parse_from_str(s, "%Y-%m-%d") { + fn column_result(value: ValueRef) -> Result { + 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))), }) @@ -39,8 +39,8 @@ 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, idx: i32) -> Result { - value.as_str(idx).and_then(|s| { + fn column_result(value: ValueRef) -> Result { + value.as_str().and_then(|s| { let fmt = match s.len() { 5 => "%H:%M", 8 => "%H:%M:%S", @@ -65,8 +65,8 @@ 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, idx: i32) -> Result { - value.as_str(idx).and_then(|s| { + fn column_result(value: ValueRef) -> Result { + 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" } else { @@ -91,10 +91,10 @@ impl ToSql for DateTime { /// RFC3339 ("YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM") into DateTime. impl FromSql for DateTime { - fn column_result(value: ValueRef, idx: i32) -> Result { + fn column_result(value: ValueRef) -> Result { { // Try to parse value as rfc3339 first. - let s = try!(value.as_str(idx)); + 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' ' { @@ -115,14 +115,14 @@ impl FromSql for DateTime { } // Couldn't parse as rfc3339 - fall back to NaiveDateTime. - NaiveDateTime::column_result(value, idx).map(|dt| UTC.from_utc_datetime(&dt)) + NaiveDateTime::column_result(value).map(|dt| UTC.from_utc_datetime(&dt)) } } /// RFC3339 ("YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM") into DateTime. impl FromSql for DateTime { - fn column_result(value: ValueRef, idx: i32) -> Result { - let utc_dt = try!(DateTime::::column_result(value, idx)); + fn column_result(value: ValueRef) -> Result { + let utc_dt = try!(DateTime::::column_result(value)); Ok(utc_dt.with_timezone(&Local)) } } diff --git a/src/types/from_sql.rs b/src/types/from_sql.rs index 09471e2..1eba548 100644 --- a/src/types/from_sql.rs +++ b/src/types/from_sql.rs @@ -4,34 +4,34 @@ use ::error::Error; /// A trait for types that can be created from a SQLite value. pub trait FromSql: Sized { - fn column_result(value: ValueRef, idx: i32) -> Result; + fn column_result(value: ValueRef) -> Result; } impl FromSql for i32 { - fn column_result(value: ValueRef, idx: i32) -> Result { - i64::column_result(value, idx).map(|i| i as i32) + fn column_result(value: ValueRef) -> Result { + i64::column_result(value).map(|i| i as i32) } } impl FromSql for i64 { - fn column_result(value: ValueRef, idx: i32) -> Result { - value.as_i64(idx) + fn column_result(value: ValueRef) -> Result { + value.as_i64() } } impl FromSql for f64 { - fn column_result(value: ValueRef, idx: i32) -> Result { + fn column_result(value: ValueRef) -> Result { match value { ValueRef::Integer(i) => Ok(i as f64), ValueRef::Real(f) => Ok(f), - _ => Err(Error::InvalidColumnType(idx, value.data_type())), + _ => Err(Error::InvalidType(value.data_type())), } } } impl FromSql for bool { - fn column_result(value: ValueRef, idx: i32) -> Result { - i64::column_result(value, idx).map(|i| match i { + fn column_result(value: ValueRef) -> Result { + i64::column_result(value).map(|i| match i { 0 => false, _ => true, }) @@ -39,28 +39,28 @@ impl FromSql for bool { } impl FromSql for String { - fn column_result(value: ValueRef, idx: i32) -> Result { - value.as_str(idx).map(|s| s.to_string()) + fn column_result(value: ValueRef) -> Result { + value.as_str().map(|s| s.to_string()) } } impl FromSql for Vec { - fn column_result(value: ValueRef, idx: i32) -> Result { - value.as_blob(idx).map(|b| b.to_vec()) + fn column_result(value: ValueRef) -> Result { + value.as_blob().map(|b| b.to_vec()) } } impl FromSql for Option { - fn column_result(value: ValueRef, idx: i32) -> Result { + fn column_result(value: ValueRef) -> Result { match value { ValueRef::Null => Ok(None), - _ => FromSql::column_result(value, idx).map(Some), + _ => FromSql::column_result(value).map(Some), } } } impl FromSql for Value { - fn column_result(value: ValueRef, _: i32) -> Result { + fn column_result(value: ValueRef) -> Result { Ok(value.into()) } } diff --git a/src/types/serde_json.rs b/src/types/serde_json.rs index 4c01f20..06d8855 100644 --- a/src/types/serde_json.rs +++ b/src/types/serde_json.rs @@ -19,11 +19,11 @@ impl ToSql for Value { /// Deserialize text/blob to JSON `Value`. impl FromSql for Value { - fn column_result(value: ValueRef, idx: i32) -> Result { + fn column_result(value: ValueRef) -> Result { match value { ValueRef::Text(ref s) => serde_json::from_str(s), ValueRef::Blob(ref b) => serde_json::from_slice(b), - _ => return Err(Error::InvalidColumnType(idx, value.data_type())), + _ => return Err(Error::InvalidType(value.data_type())), } .map_err(|err| Error::FromSqlConversionFailure(Box::new(err))) } diff --git a/src/types/time.rs b/src/types/time.rs index 05dc1b1..1f1a818 100644 --- a/src/types/time.rs +++ b/src/types/time.rs @@ -16,8 +16,8 @@ impl ToSql for time::Timespec { } impl FromSql for time::Timespec { - fn column_result(value: ValueRef, idx: i32) -> Result { - value.as_str(idx).and_then(|s| match time::strptime(s, SQLITE_DATETIME_FMT) { + fn column_result(value: ValueRef) -> Result { + 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))), }) diff --git a/src/types/value_ref.rs b/src/types/value_ref.rs index 01ae8e0..ad5b058 100644 --- a/src/types/value_ref.rs +++ b/src/types/value_ref.rs @@ -35,37 +35,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, idx: i32) -> Result { + pub fn as_i64(&self) -> Result { match *self { ValueRef::Integer(i) => Ok(i), - _ => Err(Error::InvalidColumnType(idx, self.data_type())), + _ => Err(Error::InvalidType(self.data_type())), } } /// If `self` is case `Real`, returns the floating point value. Otherwise, returns /// `Err(Error::InvalidColumnType)`. - pub fn as_f64(&self, idx: i32) -> Result { + pub fn as_f64(&self) -> Result { match *self { ValueRef::Real(f) => Ok(f), - _ => Err(Error::InvalidColumnType(idx, self.data_type())), + _ => Err(Error::InvalidType(self.data_type())), } } /// If `self` is case `Text`, returns the string value. Otherwise, returns /// `Err(Error::InvalidColumnType)`. - pub fn as_str(&self, idx: i32) -> Result<&str> { + pub fn as_str(&self) -> Result<&str> { match *self { ValueRef::Text(ref t) => Ok(t), - _ => Err(Error::InvalidColumnType(idx, self.data_type())), + _ => Err(Error::InvalidType(self.data_type())), } } /// If `self` is case `Blob`, returns the byte slice. Otherwise, returns /// `Err(Error::InvalidColumnType)`. - pub fn as_blob(&self, idx: i32) -> Result<&[u8]> { + pub fn as_blob(&self) -> Result<&[u8]> { match *self { ValueRef::Blob(ref b) => Ok(b), - _ => Err(Error::InvalidColumnType(idx, self.data_type())), + _ => Err(Error::InvalidType(self.data_type())), } } } From 91dc30b04d34f3e99099f93b15e56ccf47202704 Mon Sep 17 00:00:00 2001 From: gwenn Date: Mon, 30 May 2016 21:20:07 +0200 Subject: [PATCH 3/6] Simplify InvalidType --- src/error.rs | 10 ++++------ src/functions.rs | 2 +- src/lib.rs | 2 +- src/types/from_sql.rs | 2 +- src/types/serde_json.rs | 2 +- src/types/value_ref.rs | 8 ++++---- 6 files changed, 12 insertions(+), 14 deletions(-) diff --git a/src/error.rs b/src/error.rs index f480a42..9274217 100644 --- a/src/error.rs +++ b/src/error.rs @@ -55,7 +55,7 @@ pub enum Error { /// Error when an SQLite value is requested, but the type of the result cannot be converted to the /// requested Rust type. - InvalidType(Type), + InvalidType, /// Error when a query that was expected to insert one row did not insert any or insert many. StatementChangedRows(c_int), @@ -111,9 +111,7 @@ impl fmt::Display for Error { Error::InvalidColumnType(i, ref t) => { write!(f, "Invalid column type {} at index: {}", t, i) } - Error::InvalidType(ref t) => { - write!(f, "Invalid type {}", t) - } + 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"), @@ -147,7 +145,7 @@ 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::InvalidType => "invalid type", Error::StatementChangedRows(_) => "query inserted zero or more than one row", Error::StatementFailedToInsertRow => "statement failed to insert new row", @@ -173,7 +171,7 @@ impl error::Error for Error { Error::InvalidColumnIndex(_) | Error::InvalidColumnName(_) | Error::InvalidColumnType(_, _) | - Error::InvalidType(_) | + Error::InvalidType | Error::InvalidPath(_) | Error::StatementChangedRows(_) | Error::StatementFailedToInsertRow => None, diff --git a/src/functions.rs b/src/functions.rs index 8065e1a..55e02b2 100644 --- a/src/functions.rs +++ b/src/functions.rs @@ -218,7 +218,7 @@ 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(t) => Error::InvalidFunctionParameterType(idx, t), + Error::InvalidType => Error::InvalidFunctionParameterType(idx, value.data_type()), _ => err, }) } diff --git a/src/lib.rs b/src/lib.rs index 72e9a1f..35cfca7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1067,7 +1067,7 @@ 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(t) => Error::InvalidColumnType(idx, t), + Error::InvalidType => Error::InvalidColumnType(idx, value.data_type()), _ => err, }) } diff --git a/src/types/from_sql.rs b/src/types/from_sql.rs index 1eba548..99b3c1f 100644 --- a/src/types/from_sql.rs +++ b/src/types/from_sql.rs @@ -24,7 +24,7 @@ impl FromSql for f64 { match value { ValueRef::Integer(i) => Ok(i as f64), ValueRef::Real(f) => Ok(f), - _ => Err(Error::InvalidType(value.data_type())), + _ => Err(Error::InvalidType), } } } diff --git a/src/types/serde_json.rs b/src/types/serde_json.rs index 06d8855..c2c818d 100644 --- a/src/types/serde_json.rs +++ b/src/types/serde_json.rs @@ -23,7 +23,7 @@ impl FromSql for Value { match value { ValueRef::Text(ref s) => serde_json::from_str(s), ValueRef::Blob(ref b) => serde_json::from_slice(b), - _ => return Err(Error::InvalidType(value.data_type())), + _ => return Err(Error::InvalidType), } .map_err(|err| Error::FromSqlConversionFailure(Box::new(err))) } diff --git a/src/types/value_ref.rs b/src/types/value_ref.rs index ad5b058..e399bba 100644 --- a/src/types/value_ref.rs +++ b/src/types/value_ref.rs @@ -38,7 +38,7 @@ impl<'a> ValueRef<'a> { pub fn as_i64(&self) -> Result { match *self { ValueRef::Integer(i) => Ok(i), - _ => Err(Error::InvalidType(self.data_type())), + _ => Err(Error::InvalidType), } } @@ -47,7 +47,7 @@ impl<'a> ValueRef<'a> { pub fn as_f64(&self) -> Result { match *self { ValueRef::Real(f) => Ok(f), - _ => Err(Error::InvalidType(self.data_type())), + _ => Err(Error::InvalidType), } } @@ -56,7 +56,7 @@ impl<'a> ValueRef<'a> { pub fn as_str(&self) -> Result<&str> { match *self { ValueRef::Text(ref t) => Ok(t), - _ => Err(Error::InvalidType(self.data_type())), + _ => Err(Error::InvalidType), } } @@ -65,7 +65,7 @@ impl<'a> ValueRef<'a> { pub fn as_blob(&self) -> Result<&[u8]> { match *self { ValueRef::Blob(ref b) => Ok(b), - _ => Err(Error::InvalidType(self.data_type())), + _ => Err(Error::InvalidType), } } } From e2cf1711921090cf154f5b8c05a46357be2bda4a Mon Sep 17 00:00:00 2001 From: gwenn Date: Thu, 2 Jun 2016 21:03:25 +0200 Subject: [PATCH 4/6] Introduce `FromSqlError` as specified by John Gallagher --- src/error.rs | 26 +++++++++--------- src/functions.rs | 10 +++++-- src/lib.rs | 8 ++++-- src/types/chrono.rs | 19 ++++++------- src/types/from_sql.rs | 61 +++++++++++++++++++++++++++++++++-------- src/types/mod.rs | 2 +- src/types/serde_json.rs | 9 +++--- src/types/time.rs | 7 ++--- src/types/value_ref.rs | 19 ++++++------- 9 files changed, 100 insertions(+), 61 deletions(-) diff --git a/src/error.rs b/src/error.rs index 9274217..ef9df2d 100644 --- a/src/error.rs +++ b/src/error.rs @@ -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 when the value of a particular column is requested, but it cannot be converted to + /// the requested Rust type. + FromSqlConversionFailure(usize, Type, Box), /// 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, diff --git a/src/functions.rs b/src/functions.rs index 55e02b2..900a320 100644 --- a/src/functions.rs +++ b/src/functions.rs @@ -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) + } }) } diff --git a/src/lib.rs b/src/lib.rs index 35cfca7..ad79a8d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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) + } }) } diff --git a/src/types/chrono.rs b/src/types/chrono.rs index 3d17dd6..aec7de4 100644 --- a/src/types/chrono.rs +++ b/src/types/chrono.rs @@ -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 { + fn column_result(value: ValueRef) -> Result { 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 { + fn column_result(value: ValueRef) -> Result { 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 { + fn column_result(value: ValueRef) -> Result { 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 ToSql for DateTime { /// RFC3339 ("YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM") into DateTime. impl FromSql for DateTime { - fn column_result(value: ValueRef) -> Result { + fn column_result(value: ValueRef) -> Result { { // Try to parse value as rfc3339 first. let s = try!(value.as_str()); @@ -121,7 +120,7 @@ impl FromSql for DateTime { /// RFC3339 ("YYYY-MM-DDTHH:MM:SS.SSS[+-]HH:MM") into DateTime. impl FromSql for DateTime { - fn column_result(value: ValueRef) -> Result { + fn column_result(value: ValueRef) -> Result { let utc_dt = try!(DateTime::::column_result(value)); Ok(utc_dt.with_timezone(&Local)) } diff --git a/src/types/from_sql.rs b/src/types/from_sql.rs index 99b3c1f..ce05cb9 100644 --- a/src/types/from_sql.rs +++ b/src/types/from_sql.rs @@ -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), +} + +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; + fn column_result(value: ValueRef) -> Result; } impl FromSql for i32 { - fn column_result(value: ValueRef) -> Result { + fn column_result(value: ValueRef) -> Result { i64::column_result(value).map(|i| i as i32) } } impl FromSql for i64 { - fn column_result(value: ValueRef) -> Result { + fn column_result(value: ValueRef) -> Result { value.as_i64() } } impl FromSql for f64 { - fn column_result(value: ValueRef) -> Result { + fn column_result(value: ValueRef) -> Result { 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 { + fn column_result(value: ValueRef) -> Result { 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 { + fn column_result(value: ValueRef) -> Result { value.as_str().map(|s| s.to_string()) } } impl FromSql for Vec { - fn column_result(value: ValueRef) -> Result { + fn column_result(value: ValueRef) -> Result { value.as_blob().map(|b| b.to_vec()) } } impl FromSql for Option { - fn column_result(value: ValueRef) -> Result { + fn column_result(value: ValueRef) -> Result { match value { ValueRef::Null => Ok(None), _ => FromSql::column_result(value).map(Some), @@ -60,7 +97,7 @@ impl FromSql for Option { } impl FromSql for Value { - fn column_result(value: ValueRef) -> Result { + fn column_result(value: ValueRef) -> Result { Ok(value.into()) } } diff --git a/src/types/mod.rs b/src/types/mod.rs index 53b7b9a..b8527c2 100644 --- a/src/types/mod.rs +++ b/src/types/mod.rs @@ -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; diff --git a/src/types/serde_json.rs b/src/types/serde_json.rs index c2c818d..44a0224 100644 --- a/src/types/serde_json.rs +++ b/src/types/serde_json.rs @@ -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 { + fn column_result(value: ValueRef) -> Result { 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))) } } diff --git a/src/types/time.rs b/src/types/time.rs index 1f1a818..8ba03cf 100644 --- a/src/types/time.rs +++ b/src/types/time.rs @@ -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 { + fn column_result(value: ValueRef) -> Result { 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))), }) } } diff --git a/src/types/value_ref.rs b/src/types/value_ref.rs index e399bba..dfb28bc 100644 --- a/src/types/value_ref.rs +++ b/src/types/value_ref.rs @@ -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 { + pub fn as_i64(&self) -> Result { 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 { + pub fn as_f64(&self) -> Result { 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), } } } From 2e140d0684f332ed86d1c8448060590ea338c8ff Mon Sep 17 00:00:00 2001 From: John Gallagher Date: Sat, 31 Dec 2016 00:36:52 -0500 Subject: [PATCH 5/6] FromSqlError::cause() returns other error's cause directly (possibly None). --- src/types/from_sql.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/types/from_sql.rs b/src/types/from_sql.rs index 90c5c0f..3c78d7c 100644 --- a/src/types/from_sql.rs +++ b/src/types/from_sql.rs @@ -33,7 +33,7 @@ impl Error for FromSqlError { fn cause(&self) -> Option<&Error> { match *self { FromSqlError::InvalidType => None, - FromSqlError::Other(ref err) => Some(&**err), + FromSqlError::Other(ref err) => err.cause(), } } } From 48a84a14407f14f914aee26f2a31a4c020b2b230 Mon Sep 17 00:00:00 2001 From: John Gallagher Date: Sat, 31 Dec 2016 00:39:19 -0500 Subject: [PATCH 6/6] Add Error changes to Changelog. --- Changelog.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Changelog.md b/Changelog.md index 10a0f3f..bffa83f 100644 --- a/Changelog.md +++ b/Changelog.md @@ -9,6 +9,9 @@ and `query_row_named` now expects a `&Row` instead of a `Row`. The vast majority of calls to these functions will probably not need to change; see https://github.com/jgallagher/rusqlite/pull/184. +* BREAKING CHANGE: A few cases of the `Error` enum have sprouted additional information + (e.g., `FromSqlConversionFailure` now also includes the column index and the type returned + by SQLite). * Added `#[deprecated(since = "...", note = "...")]` flags (new in Rust 1.9 for libraries) to all deprecated APIs. * Added `query_row` convenience function to `Statement`.