Created
January 28, 2020 21:30
-
-
Save ansrivas/bdfcc358f60b23027c37957c0d917e8c to your computer and use it in GitHub Desktop.
Rust tokio-postgres example custom ToSql and FromSql implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use postgres_types::{Type, ToSql, FromSql, IsNull, to_sql_checked}; | |
use bytes::BytesMut; | |
use std::error::Error; | |
#[derive(Debug)] | |
struct RawValue<'a> { | |
type_: Type, | |
raw: Option<&'a [u8]>, | |
} | |
impl<'a> FromSql<'a> for RawValue<'a> { | |
fn from_sql( | |
type_: &Type, | |
raw: &'a [u8] | |
) -> Result<Self, Box<dyn Error + 'static + Send + Sync>> { | |
Ok(RawValue { | |
type_: type_.clone(), | |
raw: Some(raw) | |
}) | |
} | |
fn accepts(_: &Type) -> bool { | |
true | |
} | |
fn from_sql_null( | |
type_: &Type | |
) -> Result<Self, Box<dyn Error + 'static + Send + Sync>> { | |
Ok(RawValue { | |
type_: type_.clone(), | |
raw: None, | |
}) | |
} | |
} | |
impl ToSql for RawValue<'_> { | |
fn to_sql( | |
&self, | |
type_: &Type, | |
out: &mut BytesMut | |
) -> Result<IsNull, Box<dyn Error + 'static + Send + Sync>> { | |
if self.type_ != *type_ { | |
return Err(format!("expected type {} but saw {}", self.type_, type_).into()); | |
} | |
match self.raw { | |
Some(raw) => { | |
out.extend_from_slice(raw); | |
Ok(IsNull::No) | |
} | |
None => Ok(IsNull::Yes) | |
} | |
} | |
fn accepts(_: &Type) -> bool { | |
true | |
} | |
to_sql_checked!(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment