1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/**
 * Trait to convert rust enum to [postgresql
 * enum](https://www.postgresql.org/docs/current/datatype-enum.html).
 */
pub trait Enum: std::fmt::Debug {
    /** Enum name */
    fn name() -> &'static str;
    /** Convert str to enum value */
    fn from_text(value: &str) -> crate::Result<Box<Self>>;
}

/*
 * @FIXME impl FromSql/ToSql instead
 * https://github.com/rust-lang/rfcs/blob/master/text/1210-impl-specialization.md
 */
impl<E: Enum> crate::Composite for E {
    fn name() -> &'static str {
        E::name()
    }

    fn to_sql(&self) -> crate::Result<Option<Vec<u8>>> {
        use crate::ToSql;

        format!("{:?}", self).to_sql()
    }

    fn from_text(
        _: &crate::pq::Type,
        raw: Option<&str>,
    ) -> crate::Result<Box<Self>> {
        Self::from_text(crate::not_null(raw)?)
    }

    fn from_binary(
        ty: &crate::pq::Type,
        raw: Option<&[u8]>,
    ) -> crate::Result<Box<Self>> {
        use crate::FromSql;

        Self::from_text(&String::from_binary(ty, raw)?)
    }

    fn to_vec(&self) -> Vec<&dyn crate::ToSql> {
        unreachable!()
    }

    fn from_text_values(
        _: &crate::pq::Type,
        _: &[Option<&str>],
    ) -> crate::Result<Box<Self>> {
        unreachable!();
    }

    fn from_binary_values(
        _ty: &crate::pq::Type,
        _values: &[Option<&[u8]>],
    ) -> crate::Result<Box<Self>> {
        unreachable!()
    }
}

#[cfg(test)]
mod test {
    #[derive(crate::Enum, Debug, PartialEq)]
    #[r#enum(internal)]
    enum Mood {
        Sad,
        Ok,
        Happy,
    }

    crate::sql_test!(mood, super::Mood, [
        ("'Sad'", super::Mood::Sad),
        ("'Ok'", super::Mood::Ok),
        ("'Happy'", super::Mood::Happy),
    ]);
}