summaryrefslogtreecommitdiffstats
path: root/service-person/src/model/street.rs
blob: cad8e1e14c83d609749fe42b7c1ca44c33c94687 (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::streets;

#[derive(Debug, Deserialize, diesel::Identifiable, diesel::Queryable, getset::Getters)]
#[table_name = "streets"]
pub struct Street {
    pub(super) id: i32,

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

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

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

        let conn = db.get()?;

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

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