kurtbuilds / ormlite

An ORM in Rust for developers that love SQL.
https://crates.io/crates/ormlite
MIT License
216 stars 11 forks source link

support string enums #37

Open kurtbuilds opened 8 months ago

kurtbuilds commented 8 months ago

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 commented 6 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,
    }
}
netner-d commented 6 months ago

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

kurtbuilds commented 6 months ago

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.