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
use diesel::prelude::*;
use diesel::result::Error as ResultError;
use diesel::sqlite::SqliteConnection;
use diesel;
use super::schema::accounts;
#[derive(Debug, Serialize, Deserialize, Queryable, Identifiable, AsChangeset)]
pub struct Account {
pub id: i32,
pub username: String,
pub balance: i32,
}
impl Account {
pub fn all(conn: &SqliteConnection) -> Result<Vec<Account>, ResultError> {
accounts::table.load(conn)
}
pub fn find_by_username(conn: &SqliteConnection,
username: &str)
-> Result<Account, ResultError> {
accounts::table.filter(accounts::username.eq(username))
.first(conn)
}
pub fn create_from(conn: &SqliteConnection, new_account: NewAccount)
-> Result<Account, ResultError> {
diesel::insert(&new_account).into(accounts::table)
.execute(conn)?;
let account = accounts::table.order(accounts::id.desc())
.first(conn)?;
Ok(account)
}
pub fn save(&mut self, conn: &SqliteConnection) -> Result<(), ResultError> {
self.save_changes::<Account>(conn)?;
Ok(())
}
pub fn transfer(&mut self,
conn: &SqliteConnection,
other: &mut Account,
amount: i32)
-> Result<(), ResultError> {
self.balance -= amount;
other.balance += amount;
self.save(conn)?;
other.save(conn)?;
Ok(())
}
}
#[derive(Insertable)]
#[table_name="accounts"]
pub struct NewAccount<'a> {
pub username: &'a str,
pub balance: i32,
}