From 2bdb5753e9b56ec3d5f26e54c62e5133548796bf Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Sun, 24 Oct 2021 11:44:54 +0200 Subject: model: countries: Add database interfacing code Signed-off-by: Matthias Beyer --- service-person/src/model/country.rs | 46 +++++++++++++++++++++++++++++++++++-- 1 file 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 { + 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::(&conn) + .map_err(Error::from) + }) + } +} -- cgit v1.2.3