use bytes::BytesMut;
use postgres_types::{FromSql, IsNull, Json, ToSql, Type, to_sql_checked};
use std::error::Error;
pub use vld;
type BoxError = Box<dyn Error + Sync + Send>;
crate::db::__vld_db_error!(
VldPgError
);
crate::db::__vld_db_validated!(VldPgError);
crate::db::__vld_db_wrappers!(VldPgError; text: [] int: [] float: [] bool: []);
impl<S, T> ToSql for Validated<S, T>
where
T: serde::Serialize + std::fmt::Debug,
{
fn to_sql(&self, ty: &Type, out: &mut BytesMut) -> Result<IsNull, BoxError> {
Json(&self.inner).to_sql(ty, out)
}
fn accepts(ty: &Type) -> bool {
<Json<serde_json::Value> as ToSql>::accepts(ty)
}
to_sql_checked!();
}
impl<'a, S, T> FromSql<'a> for Validated<S, T>
where
S: vld::schema::VldParse,
T: serde::de::DeserializeOwned,
{
fn from_sql(ty: &Type, raw: &'a [u8]) -> Result<Self, BoxError> {
let json = serde_json::Value::from_sql(ty, raw)?;
S::vld_parse_value(&json).map_err(VldPgError::Validation)?;
Ok(Self {
inner: serde_json::from_value(json)?,
_schema: std::marker::PhantomData,
})
}
fn accepts(ty: &Type) -> bool {
<serde_json::Value as FromSql>::accepts(ty)
}
}
macro_rules! pg_scalar {
($Name:ident, $inner:ty) => {
impl<S> ToSql for $Name<S> {
fn to_sql(&self, ty: &Type, out: &mut BytesMut) -> Result<IsNull, BoxError> {
<$inner as ToSql>::to_sql(&self.value, ty, out)
}
fn accepts(ty: &Type) -> bool {
<$inner as ToSql>::accepts(ty)
}
to_sql_checked!();
}
impl<'a, S: vld::schema::VldParse> FromSql<'a> for $Name<S> {
fn from_sql(ty: &Type, raw: &'a [u8]) -> Result<Self, BoxError> {
Ok(Self::new(<$inner as FromSql>::from_sql(ty, raw)?)?)
}
fn accepts(ty: &Type) -> bool {
<$inner as FromSql>::accepts(ty)
}
}
};
}
pg_scalar!(VldText, String);
pg_scalar!(VldInt, i64);
pg_scalar!(VldFloat, f64);
pg_scalar!(VldBool, bool);
pub mod prelude {
pub use super::{Validated, VldBool, VldFloat, VldInt, VldPgError, VldText};
pub use vld::prelude::*;
}