Adding create and find_and_create impl for User
This commit is contained in:
parent
035551629c
commit
03c988dafe
|
@ -2,7 +2,10 @@ use chrono::{
|
||||||
NaiveDateTime,
|
NaiveDateTime,
|
||||||
};
|
};
|
||||||
use diesel::prelude::*;
|
use diesel::prelude::*;
|
||||||
use diesel::PgConnection;
|
use diesel::{
|
||||||
|
insert_into,
|
||||||
|
PgConnection,
|
||||||
|
};
|
||||||
|
|
||||||
#[derive(Queryable, Debug)]
|
#[derive(Queryable, Debug)]
|
||||||
pub struct User {
|
pub struct User {
|
||||||
|
@ -13,11 +16,33 @@ pub struct User {
|
||||||
pub updated_at: Option<NaiveDateTime>,
|
pub updated_at: Option<NaiveDateTime>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
use crate::schema::users;
|
||||||
|
#[table_name = "users"]
|
||||||
|
#[derive(Insertable)]
|
||||||
|
pub struct NewUser {
|
||||||
|
pub username: String,
|
||||||
|
pub is_active: bool,
|
||||||
|
}
|
||||||
|
|
||||||
impl User {
|
impl User {
|
||||||
pub fn get_with_username(conn: &PgConnection, name: String) -> QueryResult<User> {
|
pub fn get_with_username(conn: &PgConnection, name: String) -> QueryResult<User> {
|
||||||
use crate::schema::users::dsl::{ username, users };
|
use crate::schema::users::dsl::{ username, users };
|
||||||
users.filter(username.eq(&name)).first::<User>(conn)
|
users.filter(username.eq(&name)).first::<User>(conn)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn create(conn: &PgConnection, new_user: NewUser) -> QueryResult<User> {
|
||||||
|
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<User> {
|
||||||
|
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)]
|
#[derive(Queryable)]
|
||||||
|
|
Loading…
Reference in New Issue