sea-orm icon indicating copy to clipboard operation
sea-orm copied to clipboard

implement Display for enums

Open jesseduffield opened this issue 3 years ago • 5 comments

Motivation

If I create an enum through an sea-orm migration I'll get something like this auto-generated

#[derive(Debug, Clone, PartialEq, EnumIter, DeriveActiveEnum)]
#[sea_orm(rs_type = "String", db_type = "Enum", enum_name = "foo")]
pub enum Foo {
  #[sea_orm(string_value = "bar")]
  Bar,
  #[sea_orm(string_value = "baz")]
  Baz,
}

I would like for this enum to implement Display so I can go (contrived example) format!("{}", Foo::Bar) and that prints "bar".

Proposed Solutions

Not sure how this would actually be achieved

Additional Information

I'm currently using format!("{:?}", Foo::Bar) instead

Thanks!

jesseduffield avatar Aug 09 '22 06:08 jesseduffield

Hey @jesseduffield, welcome! And thanks for the suggestions!

I think we can implement Display for active enum. It will be generated by the codegen when executing sea-orm-cli generate entity. User can easily change the implementation of Display trait.

For example,

#[derive(Debug, Clone, PartialEq, EnumIter, DeriveActiveEnum)]
#[sea_orm(rs_type = "i32", db_type = "Integer")]
pub enum Color {
    #[sea_orm(num_value = 0)]
    Black,
    #[sea_orm(num_value = 1)]
    White,
}

impl std::fmt::Display for Color {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.to_value())
    }
}

#[derive(Debug, Clone, PartialEq, EnumIter, DeriveActiveEnum)]
#[sea_orm(rs_type = "String", db_type = "Enum", enum_name = "tea")]
pub enum Tea {
    #[sea_orm(string_value = "EverydayTea")]
    EverydayTea,
    #[sea_orm(string_value = "BreakfastTea")]
    BreakfastTea,
}

impl std::fmt::Display for Tea {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.to_value())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_display() {
        assert_eq!("0", format!("{}", Color::Black));
        assert_eq!("EverydayTea", format!("{}", Tea::EverydayTea));
    }
}

billy1624 avatar Aug 09 '22 10:08 billy1624

That works great, thanks

jesseduffield avatar Aug 09 '22 12:08 jesseduffield

Would you like to submit a PR for this? hahaa

billy1624 avatar Aug 09 '22 13:08 billy1624

@billy1624 if you point me in the right direction I can give it a go, though no promises on how soon I can get around to it :)

jesseduffield avatar Aug 09 '22 22:08 jesseduffield

Hey @jesseduffield, no worries! Please take your time :)

You can look into this part:

  • https://github.com/SeaQL/sea-orm/blob/be0f7b4f135da273765d34e89dcfba7dfb1aba7d/sea-orm-codegen/src/entity/active_enum.rs#L32-L42

billy1624 avatar Aug 10 '22 03:08 billy1624