psychologylib/enums/
question_type.rs

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
use serde::Deserialize;
use serde::Serialize;
use strum_macros::Display;
use strum_macros::EnumString;
#[cfg(feature = "diesel")]
use {
    diesel::backend::Backend,
    diesel::deserialize::FromSql,
    diesel::pg::Pg,
    diesel::serialize::{IsNull, Output, ToSql},
    diesel::types::Varchar,
    diesel::{deserialize, not_none, serialize},
    diesel::{AsExpression, FromSqlRow},
    std::io::Write,
};

#[derive(Debug, Display, EnumString, PartialEq, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "diesel", derive(AsExpression, FromSqlRow))]
#[cfg_attr(feature = "diesel", sql_type = "Varchar")]
pub enum QuestionType {
    YesNo,
    ChooseAnswer,
    Range,
    AgreeOrDisagree,
}

#[cfg(feature = "diesel")]
impl ToSql<Varchar, Pg> for QuestionType {
    fn to_sql<W: Write>(&self, out: &mut Output<W, Pg>) -> serialize::Result {
        match *self {
            QuestionType::YesNo => out.write_all(b"YesNo")?,
            QuestionType::ChooseAnswer => out.write_all(b"ChooseAnswer")?,
            QuestionType::Range => out.write_all(b"Range")?,
            QuestionType::AgreeOrDisagree => out.write_all(b"AgreeOrDisagree")?,
        }
        Ok(IsNull::No)
    }
}

#[cfg(feature = "diesel")]
impl FromSql<Varchar, Pg> for QuestionType {
    fn from_sql(bytes: Option<&<Pg as Backend>::RawValue>) -> deserialize::Result<Self> {
        match not_none!(bytes) {
            b"ChooseAnswer" => Ok(QuestionType::ChooseAnswer),
            b"YesNo" => Ok(QuestionType::YesNo),
            b"Range" => Ok(QuestionType::Range),
            b"AgreeOrDisagree" => Ok(QuestionType::AgreeOrDisagree),
            _ => Err("Unrecognized enum variant".into()),
        }
    }
}