pub trait QueryableByName<DB>: Sizedwhere
DB: Backend,{
// Required method
fn build<'a>(
row: &impl NamedRow<'a, DB>,
) -> Result<Self, Box<dyn Error + Send + Sync>>;
}
Expand description
Deserializes the result of a query constructed with sql_query
.
This trait can be derived
§Examples
If we just want to map a query to our struct, we can use derive
.
#[derive(QueryableByName, PartialEq, Debug)]
struct User {
id: i32,
name: String,
}
let first_user = sql_query("SELECT * FROM users ORDER BY id LIMIT 1")
.get_result(connection)?;
let expected = User { id: 1, name: "Sean".into() };
assert_eq!(expected, first_user);
If we want to do additional work during deserialization, we can use
deserialize_as
to use a different implementation.
struct LowercaseString(String);
impl Into<String> for LowercaseString {
fn into(self) -> String {
self.0
}
}
impl<DB, ST> FromSql<ST, DB> for LowercaseString
where
DB: Backend,
String: FromSql<ST, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
String::from_sql(bytes)
.map(|s| LowercaseString(s.to_lowercase()))
}
}
#[derive(QueryableByName, PartialEq, Debug)]
struct User {
id: i32,
#[diesel(deserialize_as = LowercaseString)]
name: String,
}
let first_user = sql_query("SELECT * FROM users ORDER BY id LIMIT 1")
.get_result(connection)?;
let expected = User { id: 1, name: "sean".into() };
assert_eq!(expected, first_user);
Required Methods§
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.