summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMatthias Beyer <mail@beyermatthias.de>2021-10-24 11:44:54 +0200
committerMatthias Beyer <mail@beyermatthias.de>2021-10-24 12:02:00 +0200
commit1c8be9066e50bf4eee973e1eb36b16008bc6e8ac (patch)
treefb1cd982e71812cf42015fae1f70727898ce242b
parent7e4112781b6503ae863f3861db689be888eaca2b (diff)
model: city: Add database interfacing code
Signed-off-by: Matthias Beyer <mail@beyermatthias.de>
-rw-r--r--service-person/src/model/city.rs45
1 files changed, 43 insertions, 2 deletions
diff --git a/service-person/src/model/city.rs b/service-person/src/model/city.rs
index 3c82e73..6a44292 100644
--- a/service-person/src/model/city.rs
+++ b/service-person/src/model/city.rs
@@ -1,5 +1,46 @@
use serde::Deserialize;
+use anyhow::Error;
+use anyhow::Result;
-#[derive(Debug, Deserialize)]
-pub struct City(String);
+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)
+ })
+ }
+}