summaryrefslogtreecommitdiffstats
path: root/service-person/src/model/country.rs
blob: deab6330f926c8dfe52c02d3ae905d732b931ea8 (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
41
42
43
44
45
46
47
use serde::Deserialize;
use anyhow::Error;
use anyhow::Result;

use diesel::ExpressionMethods;
use diesel::RunQueryDsl;
use diesel::query_dsl::methods::FilterDsl;
use diesel::Connection;

use crate::db::DbPool;
use crate::schema::countries;

#[derive(Debug, Deserialize, diesel::Queryable, getset::Getters)]
pub struct Country {
    id: i32,

    #[getset(get = "pub")]
    name: String,
}


#[derive(Insertable)]
#[table_name = "countries"]
struct NewCountry<'a> {
    name: &'a str
}

impl Country {
    pub fn create_or_fetch(db: &DbPool, name: &str) -> Result<Self> {
        use crate::schema;

        let conn = db.get()?;

        conn.transaction::<_, Error, _>(|| {
            let new_country = NewCountry { name };
            diesel::insert_into(schema::countries::table)
                .values(&new_country)
                .on_conflict_do_nothing()
                .execute(&conn)?;

            schema::countries::table
                .filter(schema::countries::name.eq(name))
                .first::<Country>(&conn)
                .map_err(Error::from)
        })
    }
}