summaryrefslogtreecommitdiffstats
path: root/service-person/src/model/city.rs
blob: 6a44292fb8e0465e6b50715b10187c55b6762bdc (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
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::cities;

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

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

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

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

        let conn = db.get()?;

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

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