Implement ToSql for &'a T where T: ToSql
This allows more flexible use of ToSql in generic contexts by allowing references to be used for encoding.
This commit is contained in:
parent
e9005bb176
commit
4b545ca466
@ -815,6 +815,25 @@ pub trait ToSql: fmt::Debug {
|
||||
-> Result<IsNull>;
|
||||
}
|
||||
|
||||
impl<'a, T> ToSql for &'a T where T: ToSql {
|
||||
fn to_sql_checked(&self, ty: &Type, out: &mut Write, ctx: &SessionInfo)
|
||||
-> Result<IsNull> {
|
||||
if !<&'a T as ToSql>::accepts(ty) {
|
||||
return Err(Error::WrongType(ty.clone()));
|
||||
}
|
||||
self.to_sql(ty, out, ctx)
|
||||
}
|
||||
|
||||
|
||||
fn to_sql<W: Write + ?Sized>(&self, ty: &Type, out: &mut W, ctx: &SessionInfo) -> Result<IsNull> {
|
||||
(*self).to_sql(ty, out, ctx)
|
||||
}
|
||||
|
||||
fn accepts(ty: &Type) -> bool { T::accepts(ty) }
|
||||
}
|
||||
|
||||
|
||||
|
||||
impl<T: ToSql> ToSql for Option<T> {
|
||||
to_sql_checked!();
|
||||
|
||||
|
@ -31,6 +31,14 @@ fn test_type<T: PartialEq+FromSql+ToSql, S: fmt::Display>(sql_type: &str, checks
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ref_tosql() {
|
||||
let conn = or_panic!(Connection::connect("postgres://postgres@localhost", &SslMode::None));
|
||||
let stmt = conn.prepare("SELECT $1::Int").unwrap();
|
||||
let num: &ToSql = &&7;
|
||||
stmt.query(&[num]).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bool_params() {
|
||||
test_type("BOOL", &[(Some(true), "'t'"), (Some(false), "'f'"),
|
||||
|
Loading…
Reference in New Issue
Block a user