Rework ToSql to be implementable without unsafe.

This commit is contained in:
John Gallagher
2016-05-25 22:57:43 -04:00
parent 9e49452300
commit e4926ac0d7
10 changed files with 206 additions and 122 deletions

View File

@@ -50,10 +50,8 @@
//! `FromSql` for the cases where you want to know if a value was NULL (which gets translated to
//! `None`).
pub use ffi::sqlite3_stmt;
pub use self::from_sql::FromSql;
pub use self::to_sql::ToSql;
pub use self::to_sql::{ToSql, ToSqlOutput};
pub use self::value_ref::ValueRef;
mod value_ref;
@@ -102,6 +100,42 @@ pub enum Value {
Blob(Vec<u8>),
}
impl From<Null> for Value {
fn from(_: Null) -> Value {
Value::Null
}
}
impl From<i32> for Value {
fn from(i: i32) -> Value {
Value::Integer(i as i64)
}
}
impl From<i64> for Value {
fn from(i: i64) -> Value {
Value::Integer(i)
}
}
impl From<f64> for Value {
fn from(f: f64) -> Value {
Value::Real(f)
}
}
impl From<String> for Value {
fn from(s: String) -> Value {
Value::Text(s)
}
}
impl From<Vec<u8>> for Value {
fn from(v: Vec<u8>) -> Value {
Value::Blob(v)
}
}
#[cfg(test)]
#[cfg_attr(feature="clippy", allow(similar_names))]
mod test {
@@ -111,6 +145,7 @@ mod test {
use Error;
use libc::{c_int, c_double};
use std::f64::EPSILON;
use super::Value;
fn checked_memory_handle() -> Connection {
let db = Connection::open_in_memory().unwrap();
@@ -133,6 +168,17 @@ mod test {
fn test_str() {
let db = checked_memory_handle();
let s = "hello, world!";
db.execute("INSERT INTO foo(t) VALUES (?)", &[&s]).unwrap();
let from: String = db.query_row("SELECT t FROM foo", &[], |r| r.get(0)).unwrap();
assert_eq!(from, s);
}
#[test]
fn test_string() {
let db = checked_memory_handle();
let s = "hello, world!";
db.execute("INSERT INTO foo(t) VALUES (?)", &[&s.to_owned()]).unwrap();
@@ -140,6 +186,15 @@ mod test {
assert_eq!(from, s);
}
#[test]
fn test_value() {
let db = checked_memory_handle();
db.execute("INSERT INTO foo(i) VALUES (?)", &[&Value::Integer(10)]).unwrap();
assert_eq!(10i64, db.query_row("SELECT i FROM foo", &[], |r| r.get(0)).unwrap());
}
#[test]
fn test_option() {
let db = checked_memory_handle();