]> Untitled Git - lemmy.git/blob - lemmy_db/src/source/site.rs
1224e0ab7a8fc61453f00da1590b2e514f0196f0
[lemmy.git] / lemmy_db / src / source / site.rs
1 use crate::{naive_now, schema::site, Crud};
2 use diesel::{dsl::*, result::Error, *};
3 use serde::Serialize;
4
5 #[derive(Queryable, Identifiable, PartialEq, Debug, Clone, Serialize)]
6 #[table_name = "site"]
7 pub struct Site {
8   pub id: i32,
9   pub name: String,
10   pub description: Option<String>,
11   pub creator_id: i32,
12   pub published: chrono::NaiveDateTime,
13   pub updated: Option<chrono::NaiveDateTime>,
14   pub enable_downvotes: bool,
15   pub open_registration: bool,
16   pub enable_nsfw: bool,
17   pub icon: Option<String>,
18   pub banner: Option<String>,
19 }
20
21 #[derive(Insertable, AsChangeset)]
22 #[table_name = "site"]
23 pub struct SiteForm {
24   pub name: String,
25   pub description: Option<String>,
26   pub creator_id: i32,
27   pub updated: Option<chrono::NaiveDateTime>,
28   pub enable_downvotes: bool,
29   pub open_registration: bool,
30   pub enable_nsfw: bool,
31   // when you want to null out a column, you have to send Some(None)), since sending None means you just don't want to update that column.
32   pub icon: Option<Option<String>>,
33   pub banner: Option<Option<String>>,
34 }
35
36 impl Crud<SiteForm> for Site {
37   fn read(conn: &PgConnection, _site_id: i32) -> Result<Self, Error> {
38     use crate::schema::site::dsl::*;
39     site.first::<Self>(conn)
40   }
41
42   fn create(conn: &PgConnection, new_site: &SiteForm) -> Result<Self, Error> {
43     use crate::schema::site::dsl::*;
44     insert_into(site).values(new_site).get_result::<Self>(conn)
45   }
46
47   fn update(conn: &PgConnection, site_id: i32, new_site: &SiteForm) -> Result<Self, Error> {
48     use crate::schema::site::dsl::*;
49     diesel::update(site.find(site_id))
50       .set(new_site)
51       .get_result::<Self>(conn)
52   }
53 }
54
55 impl Site {
56   pub fn transfer(conn: &PgConnection, new_creator_id: i32) -> Result<Self, Error> {
57     use crate::schema::site::dsl::*;
58     diesel::update(site.find(1))
59       .set((creator_id.eq(new_creator_id), updated.eq(naive_now())))
60       .get_result::<Self>(conn)
61   }
62
63   pub fn read_simple(conn: &PgConnection) -> Result<Self, Error> {
64     use crate::schema::site::dsl::*;
65     site.first::<Self>(conn)
66   }
67 }