mirror of
https://github.com/isar/rusqlite.git
synced 2024-11-26 19:41:37 +08:00
Better error reporting on invalid column type.
This commit is contained in:
parent
9e49452300
commit
cabcaf3dcb
21
src/error.rs
21
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),
|
||||
|
@ -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<T: FromSql>(&self, idx: usize) -> Result<T> {
|
||||
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,
|
||||
})
|
||||
}
|
||||
|
||||
|
19
src/lib.rs
19
src/lib.rs
@ -1066,7 +1066,7 @@ impl<'a, 'stmt> Row<'a, 'stmt> {
|
||||
pub fn get_checked<I: RowIndex, T: FromSql>(&self, idx: I) -> Result<T> {
|
||||
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),
|
||||
}
|
||||
|
||||
|
@ -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<Self> {
|
||||
value.as_str().and_then(|s| match NaiveDate::parse_from_str(s, "%Y-%m-%d") {
|
||||
fn column_result(value: ValueRef, idx: i32) -> Result<Self> {
|
||||
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<Self> {
|
||||
value.as_str().and_then(|s| {
|
||||
fn column_result(value: ValueRef, idx: i32) -> Result<Self> {
|
||||
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<Self> {
|
||||
value.as_str().and_then(|s| {
|
||||
fn column_result(value: ValueRef, idx: i32) -> Result<Self> {
|
||||
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<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, idx: i32) -> Result<Self> {
|
||||
{
|
||||
// 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<UTC> {
|
||||
}
|
||||
|
||||
// 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<Local>.
|
||||
impl FromSql for DateTime<Local> {
|
||||
fn column_result(value: ValueRef) -> Result<Self> {
|
||||
let utc_dt = try!(DateTime::<UTC>::column_result(value));
|
||||
fn column_result(value: ValueRef, idx: i32) -> Result<Self> {
|
||||
let utc_dt = try!(DateTime::<UTC>::column_result(value, idx));
|
||||
Ok(utc_dt.with_timezone(&Local))
|
||||
}
|
||||
}
|
||||
|
@ -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<Self>;
|
||||
fn column_result(value: ValueRef, idx: i32) -> Result<Self>;
|
||||
}
|
||||
|
||||
impl FromSql for i32 {
|
||||
fn column_result(value: ValueRef) -> Result<Self> {
|
||||
i64::column_result(value).map(|i| i as i32)
|
||||
fn column_result(value: ValueRef, idx: i32) -> Result<Self> {
|
||||
i64::column_result(value, idx).map(|i| i as i32)
|
||||
}
|
||||
}
|
||||
|
||||
impl FromSql for i64 {
|
||||
fn column_result(value: ValueRef) -> Result<Self> {
|
||||
value.as_i64()
|
||||
fn column_result(value: ValueRef, idx: i32) -> Result<Self> {
|
||||
value.as_i64(idx)
|
||||
}
|
||||
}
|
||||
|
||||
impl FromSql for f64 {
|
||||
fn column_result(value: ValueRef) -> Result<Self> {
|
||||
fn column_result(value: ValueRef, idx: i32) -> Result<Self> {
|
||||
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<Self> {
|
||||
i64::column_result(value).map(|i| match i {
|
||||
fn column_result(value: ValueRef, idx: i32) -> Result<Self> {
|
||||
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<Self> {
|
||||
value.as_str().map(|s| s.to_string())
|
||||
fn column_result(value: ValueRef, idx: i32) -> Result<Self> {
|
||||
value.as_str(idx).map(|s| s.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl FromSql for Vec<u8> {
|
||||
fn column_result(value: ValueRef) -> Result<Self> {
|
||||
value.as_blob().map(|b| b.to_vec())
|
||||
fn column_result(value: ValueRef, idx: i32) -> Result<Self> {
|
||||
value.as_blob(idx).map(|b| b.to_vec())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: FromSql> FromSql for Option<T> {
|
||||
fn column_result(value: ValueRef) -> Result<Self> {
|
||||
fn column_result(value: ValueRef, idx: i32) -> Result<Self> {
|
||||
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<Self> {
|
||||
fn column_result(value: ValueRef, _: i32) -> Result<Self> {
|
||||
Ok(value.into())
|
||||
}
|
||||
}
|
||||
|
@ -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<u8>),
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
@ -19,12 +19,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, idx: i32) -> Result<Self> {
|
||||
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)))
|
||||
_ => return Err(Error::InvalidColumnType(idx, value.data_type())),
|
||||
}
|
||||
.map_err(|err| Error::FromSqlConversionFailure(Box::new(err)))
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -16,8 +16,8 @@ impl ToSql for time::Timespec {
|
||||
}
|
||||
|
||||
impl FromSql for time::Timespec {
|
||||
fn column_result(value: ValueRef) -> Result<Self> {
|
||||
value.as_str().and_then(|s| match time::strptime(s, SQLITE_DATETIME_FMT) {
|
||||
fn column_result(value: ValueRef, idx: i32) -> Result<Self> {
|
||||
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))),
|
||||
})
|
||||
|
@ -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<i64> {
|
||||
pub fn as_i64(&self, idx: i32) -> Result<i64> {
|
||||
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<f64> {
|
||||
pub fn as_f64(&self, idx: i32) -> Result<f64> {
|
||||
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())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user