Merge pull request #983 from thomcc/value_ref-as_bytes

Add a helper function for getting the byte data from a ValueRef, regardless of if its Text or Blob
This commit is contained in:
gwenn 2021-07-03 07:23:30 +02:00 committed by GitHub
commit b3bd775f90
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 12 additions and 6 deletions

View File

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

View File

@ -77,6 +77,16 @@ impl<'a> ValueRef<'a> {
_ => 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 {