How to use sqlx::Type
with more complex scalar types?
#1502
Answered
by
thomaseizinger
thomaseizinger
asked this question in
Q&A
-
Reposting #1493. I have a Rust type that consists of multiple fields, in particular it looks like this: pub struct BitMexPriceEventId {
/// The timestamp this price event refers to.
timestamp: OffsetDateTime,
digits: usize,
} This type has a What is the best way of supporting this? Perhaps this would work? #[derive(sqlx::Type)]
#[sqlx(display_fromstr)] // name subject to bike-shedding
pub struct BitMexPriceEventId {
/// The timestamp this price event refers to.
timestamp: OffsetDateTime,
digits: usize,
} |
Beta Was this translation helpful? Give feedback.
Answered by
thomaseizinger
Nov 23, 2021
Replies: 1 comment
-
Found a way that works: macro_rules! impl_sqlx_type_display_from_str {
($ty:ty) => {
impl sqlx::Type<sqlx::Sqlite> for $ty {
fn type_info() -> sqlx::sqlite::SqliteTypeInfo {
String::type_info()
}
}
impl<'q> sqlx::Encode<'q, sqlx::Sqlite> for $ty {
fn encode_by_ref(
&self,
args: &mut Vec<sqlx::sqlite::SqliteArgumentValue<'q>>,
) -> sqlx::encode::IsNull {
self.to_string().encode_by_ref(args)
}
}
impl<'r> sqlx::Decode<'r, sqlx::Sqlite> for $ty {
fn decode(
value: sqlx::sqlite::SqliteValueRef<'r>,
) -> Result<Self, sqlx::error::BoxDynError> {
let string = String::decode(value)?;
let value = string.parse()?;
Ok(value)
}
}
};
} |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
thomaseizinger
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Found a way that works: