quannadev of gapo.tinh-te
3/16/2020 - 8:07 AM

Mysql Handle with Diesel

use diesel::{delete, insert_into, MysqlConnection, prelude::*, update};
use diesel::r2d2::ConnectionManager;
use diesel::result::Error;
use r2d2::PooledConnection;

use crate::models::users_mod;
use crate::models::users_mod::{NewUser, User};
use crate::schema::users;
use crate::schema::users::dsl::*;

type MysqlConn = PooledConnection<ConnectionManager<MysqlConnection>>;

pub struct MysqlHandle {
    pub conn: MysqlConn
}

pub trait MysqlService {
    fn get_user_by_id(&self, user_id: i32) -> Result<User, Error>;
    fn get_user_by_name(&self, name: String) -> Result<User, Error>;
    fn insert_user(&self, user: NewUser) -> Result<User, Error>;
    fn update_user(&self, user: NewUser, user_id: i32) -> Result<User, Error>;
    fn delete_user(&self, user_id: i32) -> Result<usize, Error>;
}

impl MysqlService for MysqlHandle {
    fn get_user_by_id(&self, user_id: i32) -> Result<User, Error> {
        users.find(user_id).first::<User>(&self.conn)
    }

    fn get_user_by_name(&self, name: String) -> Result<User, Error> {
        users.filter(phone.eq(name)).first::<User>(&self.conn)
    }

    fn insert_user(&self, user: NewUser) -> Result<User, Error> {
        insert_into(users).values(user.clone()).execute(&self.conn);
        self.get_user_by_name(user.phone)
    }

    fn update_user(&self, user: NewUser, user_id: i32) -> Result<User, Error> {
        update(users.find(user_id)).set(user).execute(&self.conn);
        self.get_user_by_id(user_id)
    }

    fn delete_user(&self, user_id: i32) -> Result<usize, Error> {
        delete(users.find(user_id)).execute(&self.conn)
    }
}

///Example Code
//pub fn get_example(uid: i32) {
//    let get_user = MysqlHandle { conn }.get_user_by_id(uid);
//    if get_user.is_ok() {}
//}