use diesel; use diesel::prelude::*; use schema::users; use utils; #[derive(AsChangeset, Clone, FromForm, Identifiable, Serialize, Queryable)] pub struct User { pub id: i32, pub username: String, pub realname: Option, pub email: Option, pub password: String } impl User { pub fn all(conn: utils::DbConn) -> QueryResult> { use schema::users::dsl::*; users.load::(&*conn) } pub fn by_id(user_id: i32, conn: &utils::DbConn) -> QueryResult { use schema::users::dsl::*; users.filter(id.eq(user_id)) .load::(&**conn) .map(|ref v| v[0].clone()) } pub fn by_email(user_email: &str, conn: utils::DbConn) -> QueryResult { use schema::users::dsl::*; users.filter(email.eq(user_email)) .get_result::(&*conn) } pub fn create(new_user: &NewUser, conn: utils::DbConn) -> QueryResult { use ::schema::users::dsl::*; diesel::insert_into(users) .values(new_user) .get_result(&*conn) } pub fn update(user: &User, conn: &utils::DbConn) -> QueryResult { use ::schema::users::dsl::*; user.save_changes(&*conn) } pub fn delete(user_id: i32, conn: utils::DbConn) -> QueryResult { use ::schema::users::dsl::*; diesel::delete(users.filter(id.eq(user_id))).get_result::(&*conn) } pub fn realname(&self) -> String { self.realname.as_ref().unwrap_or(&String::new()).clone() } pub fn email(&self) -> String { self.email.as_ref().unwrap_or(&String::new()).clone() } } #[derive(Default, Insertable)] #[table_name="users"] pub struct NewUser { pub username: String, pub realname: Option, pub email: Option, pub password: String, } impl NewUser { pub fn realname(&self) -> String { self.realname.as_ref().unwrap_or(&String::new()).clone() } pub fn email(&self) -> String { self.email.as_ref().unwrap_or(&String::new()).clone() } }