]> Untitled Git - lemmy.git/blob - server/src/db/category.rs
Adding emoji support
[lemmy.git] / server / src / db / category.rs
1 use schema::{category};
2 use schema::category::dsl::*;
3 use super::*;
4
5 #[derive(Queryable, Identifiable, PartialEq, Debug, Serialize, Deserialize)]
6 #[table_name="category"]
7 pub struct Category {
8   pub id: i32,
9   pub name: String
10 }
11
12 #[derive(Insertable, AsChangeset, Clone, Serialize, Deserialize)]
13 #[table_name="category"]
14 pub struct CategoryForm {
15   pub name: String,
16 }
17
18 impl Crud<CategoryForm> for Category {
19   fn read(conn: &PgConnection, category_id: i32) -> Result<Self, Error> {
20     category.find(category_id)
21       .first::<Self>(conn)
22   }
23
24   fn delete(conn: &PgConnection, category_id: i32) -> Result<usize, Error> {
25     diesel::delete(category.find(category_id))
26       .execute(conn)
27   }
28
29   fn create(conn: &PgConnection, new_category: &CategoryForm) -> Result<Self, Error> {
30       insert_into(category)
31         .values(new_category)
32         .get_result::<Self>(conn)
33   }
34
35   fn update(conn: &PgConnection, category_id: i32, new_category: &CategoryForm) -> Result<Self, Error> {
36     diesel::update(category.find(category_id))
37       .set(new_category)
38       .get_result::<Self>(conn)
39   }
40 }
41
42 impl Category {
43   pub fn list_all(conn: &PgConnection) -> Result<Vec<Self>, Error> {
44     category.load::<Self>(conn)
45   }
46 }
47
48 #[cfg(test)]
49 mod tests {
50   use super::*;
51  #[test]
52   fn test_crud() {
53     let conn = establish_connection();
54
55     let categories = Category::list_all(&conn).unwrap();
56     let expected_first_category = Category {
57       id: 1,
58       name: "Discussion".into()
59     };
60
61     assert_eq!(expected_first_category, categories[0]);
62   }
63 }