Trait diesel::deserialize::FromSql
source · pub trait FromSql<A, DB: Backend>: Sized {
fn from_sql(bytes: RawValue<'_, DB>) -> Result<Self>;
fn from_nullable_sql(bytes: Option<RawValue<'_, DB>>) -> Result<Self> { ... }
}Expand description
Deserialize a single field of a given SQL type.
When possible, implementations of this trait should prefer to use an
existing implementation, rather than reading from bytes. (For example, if
you are implementing this for an enum which is represented as an integer in
the database, prefer i32::from_sql(bytes) (or the explicit form
<i32 as FromSql<Integer, DB>>::from_sql(bytes)) over reading from bytes
directly)
Types which implement this trait should also have #[derive(FromSqlRow)]
Backend specific details
- For PostgreSQL, the bytes will be sent using the binary protocol, not text.
- For SQLite, the actual type of
DB::RawValueis private API. All implementations of this trait must be written in terms of an existing primitive. - For MySQL, the value of
byteswill depend on the return value oftype_metadatafor the given SQL type. SeeMysqlTypefor details. - For third party backends, consult that backend’s documentation.
Examples
Most implementations of this trait will be defined in terms of an existing implementation.
#[repr(i32)]
#[derive(Debug, Clone, Copy, FromSqlRow)]
pub enum MyEnum {
A = 1,
B = 2,
}
impl<DB> FromSql<Integer, DB> for MyEnum
where
DB: Backend,
i32: FromSql<Integer, DB>,
{
fn from_sql(bytes: backend::RawValue<DB>) -> deserialize::Result<Self> {
match i32::from_sql(bytes)? {
1 => Ok(MyEnum::A),
2 => Ok(MyEnum::B),
x => Err(format!("Unrecognized variant {}", x).into()),
}
}
}Required Methods§
Provided Methods§
sourcefn from_nullable_sql(bytes: Option<RawValue<'_, DB>>) -> Result<Self>
fn from_nullable_sql(bytes: Option<RawValue<'_, DB>>) -> Result<Self>
A specialized variant of from_sql for handling null values.
The default implementation returns an UnexpectedNullError for
an encountered null value and calls Self::from_sql otherwise
If your custom type supports null values you need to provide a custom implementation.