From 03c988dafec5b60dcd9968c0aad2972b2508d82c Mon Sep 17 00:00:00 2001 From: Alex Wright Date: Sun, 1 Mar 2020 20:40:49 +0100 Subject: [PATCH] Adding create and find_and_create impl for User --- src/models.rs | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/src/models.rs b/src/models.rs index d8402e9..44eb2cc 100644 --- a/src/models.rs +++ b/src/models.rs @@ -2,7 +2,10 @@ use chrono::{ NaiveDateTime, }; use diesel::prelude::*; -use diesel::PgConnection; +use diesel::{ + insert_into, + PgConnection, +}; #[derive(Queryable, Debug)] pub struct User { @@ -13,11 +16,33 @@ pub struct User { pub updated_at: Option, } +use crate::schema::users; +#[table_name = "users"] +#[derive(Insertable)] +pub struct NewUser { + pub username: String, + pub is_active: bool, +} + impl User { pub fn get_with_username(conn: &PgConnection, name: String) -> QueryResult { use crate::schema::users::dsl::{ username, users }; users.filter(username.eq(&name)).first::(conn) } + + pub fn create(conn: &PgConnection, new_user: NewUser) -> QueryResult { + use crate::schema::users::dsl::*; + let inserted = insert_into(users).values(&new_user).execute(conn)?; + println!("SQL: {}", inserted); + Self::get_with_username(conn, new_user.username) + } + + pub fn find_or_create(conn: &PgConnection, name: String) -> QueryResult { + match Self::get_with_username(conn, name.to_owned()) { + Ok(user) => Ok(user), + Err(_) => Self::create(conn, NewUser { username: name, is_active: true }), + } + } } #[derive(Queryable)]