1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
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<String>,
pub email: Option<String>,
pub password: String
}
impl User {
pub fn all(conn: utils::DbConn) -> QueryResult<Vec<User>> {
use schema::users::dsl::*;
users.load::<User>(&*conn)
}
pub fn by_id(user_id: i32, conn: &utils::DbConn) -> QueryResult<User> {
use schema::users::dsl::*;
users.filter(id.eq(user_id))
.load::<User>(&**conn)
.map(|ref v| v[0].clone())
}
pub fn by_email(user_email: &str, conn: utils::DbConn) -> QueryResult<User> {
use schema::users::dsl::*;
users.filter(email.eq(user_email))
.get_result::<User>(&*conn)
}
pub fn create(new_user: &NewUser, conn: utils::DbConn) -> QueryResult<User> {
use ::schema::users::dsl::*;
diesel::insert_into(users)
.values(new_user)
.get_result(&*conn)
}
pub fn update(user: &User, conn: &utils::DbConn) -> QueryResult<User> {
use ::schema::users::dsl::*;
user.save_changes(&*conn)
}
pub fn delete(user_id: i32, conn: utils::DbConn) -> QueryResult<User> {
use ::schema::users::dsl::*;
diesel::delete(users.filter(id.eq(user_id))).get_result::<User>(&*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<String>,
pub email: Option<String>,
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()
}
}
|