Skip to content

Commit 94f6577

Browse files
committed
Merge pull request #137 from reem/tosql-for-refs
Implement ToSql for &'a T where T: ToSql
2 parents e9005bb + 4b545ca commit 94f6577

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

src/types/mod.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -815,6 +815,25 @@ pub trait ToSql: fmt::Debug {
815815
-> Result<IsNull>;
816816
}
817817

818+
impl<'a, T> ToSql for &'a T where T: ToSql {
819+
fn to_sql_checked(&self, ty: &Type, out: &mut Write, ctx: &SessionInfo)
820+
-> Result<IsNull> {
821+
if !<&'a T as ToSql>::accepts(ty) {
822+
return Err(Error::WrongType(ty.clone()));
823+
}
824+
self.to_sql(ty, out, ctx)
825+
}
826+
827+
828+
fn to_sql<W: Write + ?Sized>(&self, ty: &Type, out: &mut W, ctx: &SessionInfo) -> Result<IsNull> {
829+
(*self).to_sql(ty, out, ctx)
830+
}
831+
832+
fn accepts(ty: &Type) -> bool { T::accepts(ty) }
833+
}
834+
835+
836+
818837
impl<T: ToSql> ToSql for Option<T> {
819838
to_sql_checked!();
820839

tests/types/mod.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,14 @@ fn test_type<T: PartialEq+FromSql+ToSql, S: fmt::Display>(sql_type: &str, checks
3131
}
3232
}
3333

34+
#[test]
35+
fn test_ref_tosql() {
36+
let conn = or_panic!(Connection::connect("postgres://postgres@localhost", &SslMode::None));
37+
let stmt = conn.prepare("SELECT $1::Int").unwrap();
38+
let num: &ToSql = &&7;
39+
stmt.query(&[num]).unwrap();
40+
}
41+
3442
#[test]
3543
fn test_bool_params() {
3644
test_type("BOOL", &[(Some(true), "'t'"), (Some(false), "'f'"),

0 commit comments

Comments
 (0)