summaryrefslogtreecommitdiffstats
path: root/service-person/src/model/person.rs
blob: 90dff1fd31b3596adf75d58ef2689a03b8d11c6a (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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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 diesel::BoolExpressionMethods;

use crate::db::DbPool;
use crate::model::Address;
use crate::schema::persons;
use crate::schema;

#[derive(Debug, Deserialize, diesel::Associations, diesel::Queryable, getset::Getters, getset::CopyGetters)]
#[belongs_to(Address)]
#[table_name = "persons"]
pub struct Person {
    id: i32,

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

    #[getset(get_copy = "pub")]
    age: i32,
    address_id: i32,
}

#[derive(Insertable)]
#[table_name = "persons"]
struct NewPerson<'a> {
    name: &'a str,
    age: i32,
    address_id: i32,
}


impl Person {
    pub fn create_or_fetch(db: &DbPool, addr: &Address, name: &str, age: i32) -> Result<Self> {
        let conn = db.get()?;

        conn.transaction::<_, Error, _>(|| {
            let new_person = NewPerson {
                name,
                age,
                address_id: addr.id,
            };

            diesel::insert_into(schema::persons::table)
                .values(&new_person)
                .on_conflict_do_nothing()
                .execute(&conn)?;

            schema::persons::table
                .filter({
                    schema::persons::name.eq(name)
                        .and(schema::persons::age.eq(age))
                        .and(schema::persons::address_id.eq(addr.id))
                })
                .first::<Person>(&conn)
                .map_err(Error::from)
        })
    }
}