aboutsummaryrefslogtreecommitdiff
path: root/src/model/report.rs
blob: e9447458c6d5fd53c93798c5cdbfeddbb4d422b3 (plain)
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
use rusqlite::types::{FromSql, FromSqlError, FromSqlResult, ValueRef};
use std::fmt;

#[derive(Debug, serde::Serialize)]
pub struct Report {
    pub date: String,
    pub name: String,
    pub amount: i64,
    pub action: Action,
}

#[derive(Debug, PartialEq, serde::Serialize)]
pub enum Action {
    Created,
    Updated,
    Deleted,
}

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

impl FromSql for Action {
    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
        match value {
            ValueRef::Text(text) => match std::str::from_utf8(text) {
                Ok("Created") => Ok(Action::Created),
                Ok("Updated") => Ok(Action::Updated),
                Ok("Deleted") => Ok(Action::Deleted),
                Ok(str) => Err(FromSqlError::Other(
                    format!("Unknown action: {str}").into(),
                )),
                Err(err) => Err(FromSqlError::Other(err.into())),
            },
            _ => Err(FromSqlError::InvalidType),
        }
    }
}