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
|
use schema::posts;
use diesel::prelude::*;
use diesel;
use utils;
#[derive(AsChangeset, FromForm, Identifiable, Serialize, Queryable)]
pub struct Post {
pub id: i32,
pub title: String,
pub body: String,
pub published: bool,
}
#[derive(Default, FromForm, Insertable)]
#[table_name="posts"]
pub struct NewPost {
pub title: String,
pub body: String,
pub published: bool,
}
impl Post {
pub fn get_all(conn: utils::DbConn) -> Vec<Post> {
use ::schema::posts::dsl::*;
posts.filter(published.eq(false))
.limit(5)
.load::<Post>(&*conn)
.expect("Error loading posts")
}
fn get_internal(post_id: i32, conn: &utils::DbConn) -> Post {
use ::schema::posts::dsl::*;
posts.find(post_id)
.get_result(&**conn)
.expect(&format!("Unable to find post with id={}", post_id))
}
pub fn get(post_id: i32, conn: utils::DbConn) -> Post {
Post::get_internal(post_id, &conn)
}
pub fn create(new_post: &NewPost, conn: utils::DbConn) {
use ::schema::posts::dsl::*;
diesel::insert_into(posts)
.values(new_post)
.execute(&*conn)
.expect("Error saving post.");
}
pub fn update(updated_post: &Post, conn: utils::DbConn) {
let p = Post::get_internal(updated_post.id, &conn);
diesel::update(&p)
.set(updated_post)
.execute(&*conn)
.expect("Error saving post.");
}
pub fn delete(post_id: i32, conn: utils::DbConn) {
use ::schema::posts::dsl::*;
diesel::delete(posts.filter(id.eq(post_id)))
.execute(&*conn)
.expect(&format!("Could not delete post with id {}", post_id));
}
}
|