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

Make text based enum as Derive macro #1

Open
Kilerd opened this issue Jan 31, 2023 — with GitHub Codespaces · 0 comments
Open

Make text based enum as Derive macro #1

Kilerd opened this issue Jan 31, 2023 — with GitHub Codespaces · 0 comments

Comments

Copy link
Owner

Kilerd commented Jan 31, 2023

currently sqlx only support enum defined in postgres, but it's not convenient for those "enum" in rust but stored as text/varchar in postgres, what I call as TextEnum, this trait should be derived via proc macro.

we do have a version of declare macro

macro_rules! as_sql_text {
    ($ident:ident) => {
        impl ::sqlx::Type<::sqlx::Postgres> for $ident {
            fn type_info() -> ::sqlx::postgres::PgTypeInfo {
                ::sqlx::postgres::PgTypeInfo::with_oid(1043)
            }
        }

        impl sqlx::Decode<'_, ::sqlx::Postgres> for $ident {
            fn decode(
                value: <::sqlx::Postgres as ::sqlx::database::HasValueRef<'_>>::ValueRef,
            ) -> Result<Self, ::sqlx::error::BoxDynError> {
                use std::str::FromStr;
                let value = <&str as ::sqlx::Decode<::sqlx::Postgres>>::decode(value)?;
                Ok(Self::from_str(value)?)
            }
        }

        impl sqlx::Encode<'_, ::sqlx::Postgres> for $ident {
            fn encode_by_ref(
                &self, buf: &mut <::sqlx::Postgres as ::sqlx::database::HasArguments<'_>>::ArgumentBuffer,
            ) -> ::sqlx::encode::IsNull {
                let x: &str = self.as_ref();
                <&str as ::sqlx::Encode<::sqlx::Postgres>>::encode_by_ref(&x, buf)
            }
        }
    };
}
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

No branches or pull requests

1 participant