Skip to content
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

Open
kurtbuilds opened this issue Nov 11, 2023 · 3 comments · May be fixed by #59
Open

support string enums #37

kurtbuilds opened this issue Nov 11, 2023 · 3 comments · May be fixed by #59

Comments

@kurtbuilds
Copy link
Owner

kurtbuilds commented Nov 11, 2023

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.

@netner-d
Copy link

netner-d commented Jan 12, 2024

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,
    }
}

@netner-d
Copy link

@kurtbuilds if you're not already working on it I'll work on this this WE

@kurtbuilds
Copy link
Owner Author

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.

@eboody eboody linked a pull request Dec 5, 2024 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants