blob: 688eeaf2df9e33f82080970ab6be339c598147fa (
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 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, diesel::Identifiable, diesel::Queryable, getset::Getters)]
#[table_name = "cities"]
pub struct City {
pub(super) 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)
})
}
}
|