Open kurtbuilds opened 8 months ago
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.
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.
We should make an
ormlite::Type
macro to autogen most of this.