Electron100 / butane

An ORM for Rust with a focus on simplicity and on writing Rust, not SQL
Apache License 2.0
91 stars 13 forks source link

Support for simple enums of a single type #20

Closed jayvdb closed 1 year ago

jayvdb commented 1 year ago

afaics, enums consisting of a single type are not yet automatically supported. I can implement ToSql, but it would be nice to not need to. I see there is a #[butane_type(Text)], but it doesnt appear to help here. I have serde Serialize and Deserialize for the enum, and ToString/FromStr, but I get the error below.

    #[derive(
        Clone,
        Copy,
        Debug,
        Deserialize,
        Eq,
        Hash,
        Ord,
        PartialEq,
        PartialOrd,
        Serialize,
    )]
    pub enum FormatEnum {
        #[serde(rename = "tif")]
        Tif,
        #[serde(rename = "png")]
        Png,
    }

    impl ToString for FormatEnum {
        fn to_string(&self) -> String {
            match *self {
                Self::Tif => "tif".to_string(),
                Self::Png => "png".to_string(),
            }
        }
    }

    impl std::str::FromStr for FormatEnum {
        type Err = &'static str;
        fn from_str(value: &str) -> Result<Self, Self::Err> {
            match value {
                "tif" => Ok(Self::Tif),
                "png" => Ok(Self::Png),
                _ => Err("invalid value"),
            }
        }
    }

    impl Default for FormatEnum {
        fn default() -> Self {
            FormatEnum::Tif
        }
    }

error:

error[E0277]: the trait bound `FormatEnum: ToSql` is not satisfied
   --> rust/models/src/lib.rs:388:5
    |
388 |     #[model]
    |     ^^^^^^^^ the trait `ToSql` is not implemented for `FormatEnum`
    |
    = help: the following other types implement trait `ToSql`:
              ...
            and 32 others
    = note: required for `std::option::Option<FormatEnum>` to implement `ToSql`
    = note: required for `SqlVal` to implement `From<std::option::Option<FormatEnum>>`
    = note: required for `std::option::Option<FormatEnum>` to implement `Into<SqlVal>`

enums are mentioned at https://github.com/Electron100/butane/blob/master/notes.org#roadmap

jayvdb commented 1 year ago

fwiw, diesel also doesnt automatically support enums. https://github.com/terry90/diesel-enum-derive and similar are required to avoid writing boilerplate code.