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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
|
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::City;
use crate::model::Country;
use crate::model::Street;
use crate::schema::address;
use crate::schema;
#[derive(Debug, diesel::Associations, diesel::Queryable, getset::CopyGetters)]
#[belongs_to(Country)]
#[belongs_to(City)]
#[belongs_to(Street)]
#[table_name = "address"]
pub struct Address {
pub(super) id: i32,
country_id: i32,
city_id: i32,
street_id: i32,
#[getset(get_copy = "pub")]
addr_number: i32,
}
#[derive(Insertable)]
#[table_name = "address"]
struct NewAddress {
country_id: i32,
city_id: i32,
street_id: i32,
addr_number: i32,
}
impl Address {
pub fn create_or_fetch(db: &DbPool, country: &Country, city: &City, street: &Street, number: i32) -> Result<Self> {
let conn = db.get()?;
conn.transaction::<_, Error, _>(|| {
let new_address = NewAddress {
country_id: country.id,
city_id: city.id,
street_id: street.id,
addr_number: number,
};
diesel::insert_into(schema::address::table)
.values(&new_address)
.on_conflict_do_nothing()
.execute(&conn)?;
schema::address::table
.filter({
schema::address::country_id.eq(country.id)
.and(schema::address::city_id.eq(city.id))
.and(schema::address::street_id.eq(street.id))
.and(schema::address::addr_number.eq(number))
})
.first::<Address>(&conn)
.map_err(Error::from)
})
}
pub fn country(&self, db: &DbPool) -> Result<Country> {
schema::countries::table
.filter(schema::countries::id.eq(self.country_id))
.first::<Country>(&db.get()?)
.map_err(Error::from)
}
pub fn city(&self, db: &DbPool) -> Result<City> {
schema::cities::table
.filter(schema::cities::id.eq(self.city_id))
.first::<City>(&db.get()?)
.map_err(Error::from)
}
pub fn street(&self, db: &DbPool) -> Result<Street> {
schema::streets::table
.filter(schema::streets::id.eq(self.street_id))
.first::<Street>(&db.get()?)
.map_err(Error::from)
}
}
|