ormlite
ormlite copied to clipboard
support string enums
This is the code required to create a user role enum, if we want it to be just a VARCHAR in the database, rather than a postgresql enum.
#[derive(
Debug,
Serialize,
Deserialize,
PartialEq,
Clone,
Copy,
PartialOrd,
ManualType,
EnumString,
IntoStaticStr,
)]
#[strum(serialize_all = "snake_case")]
pub enum Role {
OrgAdmin,
User,
}
impl sqlx::Encode<'_, Postgres> for Role {
fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> sqlx::encode::IsNull {
<&'static str as sqlx::Encode<Postgres>>::encode(self.into(), buf)
}
}
impl sqlx::Decode<'_, Postgres> for Role {
fn decode(value: PgValueRef<'_>) -> Result<Self, sqlx::error::BoxDynError> {
Ok(Self::from_str(value.as_str()?)?)
}
}
impl sqlx::Type<Postgres> for Role {
fn type_info() -> <Postgres as sqlx::Database>::TypeInfo {
<String as sqlx::Type<Postgres>>::type_info()
}
fn compatible(ty: &<Postgres as sqlx::Database>::TypeInfo) -> bool {
<String as sqlx::Type<Postgres>>::compatible(ty)
}
}
We should make an ormlite::Type
macro to autogen most of this.
hey for people in need of a quick and dirty declarative macro fix waiting for a proc one
macro_rules! string_enum {
(pub enum $name:ident {
$($variant:ident),*,
}) => {
#[derive(
Debug,
Clone,
Copy,
PartialEq,
PartialOrd,
ormlite::types::ManualType,
serde::Serialize,
serde::Deserialize,
strum::EnumString,
strum::IntoStaticStr,
)]
#[strum(serialize_all = "snake_case")]
pub enum $name {
$($variant),*
}
impl $name {
pub fn from_str(value: &str) -> anyhow::Result<Self> {
$name::try_from(value).map_err(|_| anyhow::Error::msg("Invalid variant."))
}
}
impl sqlx::Encode<'_, sqlx::Postgres> for $name {
fn encode_by_ref(
&self,
buf: &mut sqlx::postgres::PgArgumentBuffer,
) -> sqlx::encode::IsNull {
<&'static str as sqlx::Encode<sqlx::Postgres>>::encode(self.into(), buf)
}
}
impl sqlx::Decode<'_, sqlx::Postgres> for $name {
fn decode(
value: sqlx::postgres::PgValueRef<'_>,
) -> Result<Self, sqlx::error::BoxDynError> {
Ok(Self::from_str(value.as_str()?)?)
}
}
impl sqlx::Type<sqlx::Postgres> for $name {
fn type_info() -> <sqlx::Postgres as sqlx::Database>::TypeInfo {
<String as sqlx::Type<sqlx::Postgres>>::type_info()
}
fn compatible(ty: &<sqlx::Postgres as sqlx::Database>::TypeInfo) -> bool {
<String as sqlx::Type<sqlx::Postgres>>::compatible(ty)
}
}
};
}
string_enum! {
pub enum UserType {
Admin,
Pro,
Private,
}
}
@kurtbuilds if you're not already working on it I'll work on this this WE
I'm not; I'd welcome a PR.
One note: I haven't investigated this in detail, so I could very well be entirely wrong, but my sense is that the strum macro slows down both compilation and my editor (IntelliJ) for unknown reasons. If you implement this, it might be smart to eschew it as a dependency and directly (re)-implement any necessary functionality from it.