-
Notifications
You must be signed in to change notification settings - Fork 14
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
support string enums #37
Comments
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.The text was updated successfully, but these errors were encountered: