How to use a custom type with sqlx?

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 :slight_smile:

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
        Self: Sized,

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)?;


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:

  1. Is implementing the sqlx::Encode and sqlx::Decode trait the correct way of handling a custom type with sqlx?
  2. If 1 is the case: How to implement sqlx::Encode if I simply want to save the cron expression as string (in a varchar column) to the database?

Thanks in advance for your help. I really appreciate it :slight_smile: