diff options
-rw-r--r-- | service-person/src/model/country.rs | 46 |
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) + }) + } +} |