Hi,
for the past few days I've been exploring sqlx
for the first time as an alternative to diesel
which has been what I've used in the past and so far I'm really enyoing it
Today I tried to use a custom struct and implement some traits to be able to directly use that struct with sqlx
. This looks something like this:
#[derive(sqlx::FromRow, Debug)]
pub struct ScheduledJob {
pub id: Uuid,
pub cron: Cron,
...
}
#[derive(Debug, Clone)]
pub struct Cron(cron::Schedule);
impl<'r> sqlx::Encode<'r, Postgres> for Cron {
fn encode(self, buf: &mut <Postgres as sqlx::database::HasArguments<'r>>::ArgumentBuffer) -> sqlx::encode::IsNull
where
Self: Sized,
{
todo!()
}
}
impl<'r> sqlx::Decode<'r, Postgres> for Cron {
fn decode(value: <Postgres as sqlx::database::HasValueRef<'r>>::ValueRef) -> Result<Self, sqlx::error::BoxDynError> {
let cron_expression = <&str as sqlx::Decode<Postgres>>::decode(value)?;
let schedule = cron::Schedule::from_str(cron_expression)?;
Ok(Cron(schedule))
}
}
Retrieving and parsing the cron expression from the database works, but I didn't find any examples on how to implement the sqlx::Encode
trait.
Therefore I have two questions:
- Is implementing the
sqlx::Encode
andsqlx::Decode
trait the correct way of handling a custom type withsqlx
? - If 1 is the case: How to implement
sqlx::Encode
if I simply want to save the cron expression as string (in avarchar
column) to the database?
Thanks in advance for your help. I really appreciate it