]> Untitled Git - lemmy.git/blob - crates/db_views_moderator/src/mod_remove_community_view.rs
Add diesel_async, get rid of blocking function (#2510)
[lemmy.git] / crates / db_views_moderator / src / mod_remove_community_view.rs
1 use crate::structs::{ModRemoveCommunityView, ModlogListParams};
2 use diesel::{
3   result::Error,
4   BoolExpressionMethods,
5   ExpressionMethods,
6   IntoSql,
7   JoinOnDsl,
8   NullableExpressionMethods,
9   QueryDsl,
10 };
11 use diesel_async::RunQueryDsl;
12 use lemmy_db_schema::{
13   newtypes::PersonId,
14   schema::{community, mod_remove_community, person},
15   source::{
16     community::{Community, CommunitySafe},
17     moderator::ModRemoveCommunity,
18     person::{Person, PersonSafe},
19   },
20   traits::{ToSafe, ViewToVec},
21   utils::{get_conn, limit_and_offset, DbPool},
22 };
23
24 type ModRemoveCommunityTuple = (ModRemoveCommunity, Option<PersonSafe>, CommunitySafe);
25
26 impl ModRemoveCommunityView {
27   pub async fn list(pool: &DbPool, params: ModlogListParams) -> Result<Vec<Self>, Error> {
28     let conn = &mut get_conn(pool).await?;
29     let admin_person_id_join = params.mod_person_id.unwrap_or(PersonId(-1));
30     let show_mod_names = !params.hide_modlog_names;
31     let show_mod_names_expr = show_mod_names.as_sql::<diesel::sql_types::Bool>();
32
33     let admin_names_join = mod_remove_community::mod_person_id
34       .eq(person::id)
35       .and(show_mod_names_expr.or(person::id.eq(admin_person_id_join)));
36     let mut query = mod_remove_community::table
37       .left_join(person::table.on(admin_names_join))
38       .inner_join(community::table)
39       .select((
40         mod_remove_community::all_columns,
41         Person::safe_columns_tuple().nullable(),
42         Community::safe_columns_tuple(),
43       ))
44       .into_boxed();
45
46     if let Some(mod_person_id) = params.mod_person_id {
47       query = query.filter(mod_remove_community::mod_person_id.eq(mod_person_id));
48     };
49
50     let (limit, offset) = limit_and_offset(params.page, params.limit)?;
51
52     let res = query
53       .limit(limit)
54       .offset(offset)
55       .order_by(mod_remove_community::when_.desc())
56       .load::<ModRemoveCommunityTuple>(conn)
57       .await?;
58
59     let results = Self::from_tuple_to_vec(res);
60     Ok(results)
61   }
62 }
63
64 impl ViewToVec for ModRemoveCommunityView {
65   type DbTuple = ModRemoveCommunityTuple;
66   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
67     items
68       .into_iter()
69       .map(|a| Self {
70         mod_remove_community: a.0,
71         moderator: a.1,
72         community: a.2,
73       })
74       .collect::<Vec<Self>>()
75   }
76 }