models.rs 2.75 KB
use std::sync::Arc;
use crate::schema::*;
use crate::error::Error;
use crate::Pool;
use diesel::prelude::*;
use diesel::{
    dsl::{delete, insert_into, update},
    RunQueryDsl
};
use serde::{Deserialize, Serialize};


#[derive(Debug, Serialize, Deserialize, Queryable, Identifiable)]
pub struct User {
    pub id: i32,
    pub name: String,
    pub address: String,
    pub date_created: String,
}

#[derive(Debug, Insertable)]
#[table_name = "users"]
pub struct UserNew<'a> {
    pub name: &'a str,
    pub address: &'a str,
    pub date_created: &'a str,
}

#[derive(Debug, Serialize, Deserialize, AsChangeset)]
#[table_name="users"]
pub struct UserJson {
    pub name: String,
    pub address: String,
}

pub(crate) enum Action {
    Created(User),
    Found(User),
}


pub(crate) fn create_user( pool: Arc<Pool>
                         , item: UserJson ) -> Result<Action, Error> {
    use crate::schema::users::dsl::*;
    let db_connection = pool.get()?;

    match users . filter(name.eq(&item.name))
                . first::<User>(&db_connection)
    {
        Ok(result) => Ok(Action::Found(result)),
        Err(_)     => {
            let now = chrono::Local::now().naive_local();
            let new_user = UserNew {
                name:         &item.name,
                address:      &item.address,
                date_created: &format!("{}", now),
            };

            Ok(Action::Created(db_connection.transaction(|| {
                insert_into(users) . values(&new_user)
                                   . execute(&db_connection)?;

                users . order(id.desc())
                      . first::<User>(&db_connection)
            })?))
        }
    }
}

pub(crate) fn get_users(pool: Arc<Pool>) -> Result<Vec<User>, Error>
{
    use crate::schema::users::dsl::*;
    let db_connection = pool.get()?;
    Ok(users.load::<User>(&db_connection)?)
}

pub(crate) fn get_user( pool:  Arc<Pool>
                      , ident: i32 ) -> Result<User, Error>
{
    use crate::schema::users::dsl::*;
    let db_connection = pool.get()?;
    Ok(users.find(ident).first::<User>(&db_connection)?)
}

pub(crate) fn delete_user( pool: Arc<Pool>
                         , ident: i32 ) -> Result<usize, Error>
{
    use crate::schema::users::dsl::*;
    let db_connection = pool.get()?;
    Ok(delete(users.find(ident)).execute(&db_connection)?)
}

pub(crate) fn update_user( pool: Arc<Pool>
                         , ident: i32
                         , item: UserJson ) -> Result<User, Error>
{
    use crate::schema::users::dsl::*;
    let db_connection = pool.get()?;
    let mut user = users.find(ident).first::<User>(&db_connection)?;

    update(users.find(ident)).set(&item).execute(&db_connection)?;
    user.name    = item.name;
    user.address = item.address;

    Ok(user)
}