about summary refs log tree commit diff stats
path: root/crates/rocie-server/src/storage/sql/unit.rs
blob: fe00b1bb5c0d12ced16932521cfd3740c3ae8532 (plain) (blame)
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
use std::{fmt::Display, str::FromStr};

use serde::{Deserialize, Serialize};
use sqlx::{Database, Encode, Type};
use utoipa::ToSchema;
use uuid::Uuid;

#[derive(ToSchema, Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Serialize, Deserialize)]
pub(crate) struct Unit {
    pub(crate) id: UnitId,
    pub(crate) full_name_singular: String,
    pub(crate) full_name_plural: String,
    pub(crate) short_name: String,
    pub(crate) description: Option<String>,
}

#[derive(
    Deserialize, Serialize, Debug, Default, ToSchema, Clone, Copy, PartialEq, Eq, PartialOrd, Ord,
)]
pub(crate) struct UnitId(Uuid);

impl UnitId {
    pub(crate) fn from_db(id: &str) -> UnitId {
        Self(Uuid::from_str(id).expect("We put an uuid into the db, it should also go out again"))
    }
}

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

impl From<Uuid> for UnitId {
    fn from(value: Uuid) -> Self {
        Self(value)
    }
}

impl<'q, DB: Database> Encode<'q, DB> for UnitId
where
    String: Encode<'q, DB>,
{
    fn encode_by_ref(
        &self,
        buf: &mut <DB as Database>::ArgumentBuffer<'q>,
    ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> {
        let inner = self.0.to_string();
        Encode::<DB>::encode_by_ref(&inner, buf)
    }
}
impl<DB: Database> Type<DB> for UnitId
where
    String: Type<DB>,
{
    fn type_info() -> DB::TypeInfo {
        <String as Type<DB>>::type_info()
    }
}