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
commit2bdb5753e9b56ec3d5f26e54c62e5133548796bf (patch)
tree602d7db5f90d4388cad54c83d2494f3c8f3d2fe7
parent1c8be9066e50bf4eee973e1eb36b16008bc6e8ac (diff)
model: countries: Add database interfacing code
Signed-off-by: Matthias Beyer <mail@beyermatthias.de>
-rw-r--r--service-person/src/model/country.rs46
1 files changed, 44 insertions, 2 deletions
diff --git a/service-person/src/model/country.rs b/service-person/src/model/country.rs
index b642bf7..deab633 100644
--- a/service-person/src/model/country.rs
+++ b/service-person/src/model/country.rs
@@ -1,5 +1,47 @@
use serde::Deserialize;
+use anyhow::Error;
+use anyhow::Result;
-#[derive(Debug, Deserialize)]
-pub struct Country(String);
+use diesel::ExpressionMethods;
+use diesel::RunQueryDsl;
+use diesel::query_dsl::methods::FilterDsl;
+use diesel::Connection;
+use crate::db::DbPool;
+use crate::schema::countries;
+
+#[derive(Debug, Deserialize, diesel::Queryable, getset::Getters)]
+pub struct Country {
+ id: i32,
+
+ #[getset(get = "pub")]
+ name: String,
+}
+
+
+#[derive(Insertable)]
+#[table_name = "countries"]
+struct NewCountry<'a> {
+ name: &'a str
+}
+
+impl Country {
+ pub fn create_or_fetch(db: &DbPool, name: &str) -> Result<Self> {
+ use crate::schema;
+
+ let conn = db.get()?;
+
+ conn.transaction::<_, Error, _>(|| {
+ let new_country = NewCountry { name };
+ diesel::insert_into(schema::countries::table)
+ .values(&new_country)
+ .on_conflict_do_nothing()
+ .execute(&conn)?;
+
+ schema::countries::table
+ .filter(schema::countries::name.eq(name))
+ .first::<Country>(&conn)
+ .map_err(Error::from)
+ })
+ }
+}