Add a helper function for getting the byte data from a value ref regardless of if its Text or Blob

This commit is contained in:
Thom Chiovoloni 2021-07-02 17:12:05 -07:00
parent dcaa67a617
commit 15d3ae30e3
2 changed files with 12 additions and 6 deletions

View File

@ -17,12 +17,8 @@ impl ToSql for Value {
impl FromSql for Value { impl FromSql for Value {
#[inline] #[inline]
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> { fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
match value { let bytes = value.as_bytes()?;
ValueRef::Text(s) => serde_json::from_slice(s), serde_json::from_slice(bytes).map_err(|err| FromSqlError::Other(Box::new(err)))
ValueRef::Blob(b) => serde_json::from_slice(b),
_ => return Err(FromSqlError::InvalidType),
}
.map_err(|err| FromSqlError::Other(Box::new(err)))
} }
} }

View File

@ -77,6 +77,16 @@ impl<'a> ValueRef<'a> {
_ => Err(FromSqlError::InvalidType), _ => Err(FromSqlError::InvalidType),
} }
} }
/// Returns the byte slice that makes up this ValueRef if it's either
/// [`ValueRef::Blob`] or [`ValueRef::Text`].
#[inline]
pub fn as_bytes(&self) -> FromSqlResult<&'a [u8]> {
match self {
ValueRef::Text(s) | ValueRef::Blob(s) => Ok(s),
_ => Err(FromSqlError::InvalidType),
}
}
} }
impl From<ValueRef<'_>> for Value { impl From<ValueRef<'_>> for Value {