models.rs
2.75 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
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)
}