How do you write out a string based enum for postgres using diesel?
The code I have is below. The examples I found seem to be based around diesel 1, but the documentation samples for diesel v2.X.X only offer a tiny snippet of code that by itself isn’t usable and I don’t know how to bridge the gap to a working sample.
This doesn’t need to be generic for all Backend
just postgres.
#[derive(Debug, Clone, Copy, AsExpression)]
#[diesel(sql_type = Text)]
pub enum EnumStatus {
OPEN,
CLOSED,
}
impl<DB> ToSql<Text, DB> for EnumStatus
where
DB: Backend,
String: ToSql<Text, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> serialize::Result {
match self {
EnumStatus::OPEN => b"OPEN".to_sql(out),
EnumStatus::CLOSED => b"CLOSED".to_sql(out),
}
}
}
impl<DB> FromSql<Text, DB> for EnumStatus
where
DB: Backend,
String: FromSql<Text, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
match String::from_sql(bytes)? {
b"OPEN" => Ok(EnumStatus::OPEN),
b"CLOSED" => Ok(EnumStatus::CLOSED),
x => Err(format!("Unrecognized enum - {}", x).into()),
}
}
}