]> Untitled Git - lemmy.git/blob - crates/db_views_actor/src/person_view.rs
Use same table join code for both read and list functions (#3663)
[lemmy.git] / crates / db_views_actor / src / person_view.rs
1 use crate::structs::PersonView;
2 use diesel::{
3   dsl::now,
4   pg::Pg,
5   result::Error,
6   BoolExpressionMethods,
7   ExpressionMethods,
8   PgTextExpressionMethods,
9   QueryDsl,
10 };
11 use diesel_async::RunQueryDsl;
12 use lemmy_db_schema::{
13   aggregates::structs::PersonAggregates,
14   newtypes::PersonId,
15   schema,
16   schema::{person, person_aggregates},
17   source::person::Person,
18   traits::JoinView,
19   utils::{fuzzy_search, get_conn, limit_and_offset, DbConn, DbPool, ListFn, Queries, ReadFn},
20   PersonSortType,
21 };
22
23 type PersonViewTuple = (Person, PersonAggregates);
24
25 enum ListMode {
26   Admins,
27   Banned,
28   Query(PersonQuery),
29 }
30
31 fn queries<'a>(
32 ) -> Queries<impl ReadFn<'a, PersonView, PersonId>, impl ListFn<'a, PersonView, ListMode>> {
33   let all_joins = |query: person::BoxedQuery<'a, Pg>| {
34     query
35       .inner_join(person_aggregates::table)
36       .select((person::all_columns, person_aggregates::all_columns))
37   };
38
39   let read = move |mut conn: DbConn<'a>, person_id: PersonId| async move {
40     all_joins(person::table.find(person_id).into_boxed())
41       .first::<PersonViewTuple>(&mut conn)
42       .await
43   };
44
45   let list = move |mut conn: DbConn<'a>, mode: ListMode| async move {
46     let mut query = all_joins(person::table.into_boxed());
47     match mode {
48       ListMode::Admins => {
49         query = query
50           .filter(person::admin.eq(true))
51           .filter(person::deleted.eq(false))
52           .order_by(person::published);
53       }
54       ListMode::Banned => {
55         query = query
56           .filter(
57             person::banned.eq(true).and(
58               person::ban_expires
59                 .is_null()
60                 .or(person::ban_expires.gt(now)),
61             ),
62           )
63           .filter(person::deleted.eq(false));
64       }
65       ListMode::Query(options) => {
66         if let Some(search_term) = options.search_term {
67           let searcher = fuzzy_search(&search_term);
68           query = query
69             .filter(person::name.ilike(searcher.clone()))
70             .or_filter(person::display_name.ilike(searcher));
71         }
72
73         query = match options.sort.unwrap_or(PersonSortType::CommentScore) {
74           PersonSortType::New => query.order_by(person::published.desc()),
75           PersonSortType::Old => query.order_by(person::published.asc()),
76           PersonSortType::MostComments => query.order_by(person_aggregates::comment_count.desc()),
77           PersonSortType::CommentScore => query.order_by(person_aggregates::comment_score.desc()),
78           PersonSortType::PostScore => query.order_by(person_aggregates::post_score.desc()),
79           PersonSortType::PostCount => query.order_by(person_aggregates::post_count.desc()),
80         };
81
82         let (limit, offset) = limit_and_offset(options.page, options.limit)?;
83         query = query.limit(limit).offset(offset);
84       }
85     }
86     query.load::<PersonViewTuple>(&mut conn).await
87   };
88
89   Queries::new(read, list)
90 }
91
92 impl PersonView {
93   pub async fn read(pool: &mut DbPool<'_>, person_id: PersonId) -> Result<Self, Error> {
94     queries().read(pool, person_id).await
95   }
96
97   pub async fn is_admin(pool: &mut DbPool<'_>, person_id: PersonId) -> Result<bool, Error> {
98     use schema::person::dsl::{admin, id, person};
99     let conn = &mut get_conn(pool).await?;
100     let is_admin = person
101       .filter(id.eq(person_id))
102       .select(admin)
103       .first::<bool>(conn)
104       .await?;
105     Ok(is_admin)
106   }
107
108   pub async fn admins(pool: &mut DbPool<'_>) -> Result<Vec<Self>, Error> {
109     queries().list(pool, ListMode::Admins).await
110   }
111
112   pub async fn banned(pool: &mut DbPool<'_>) -> Result<Vec<Self>, Error> {
113     queries().list(pool, ListMode::Banned).await
114   }
115 }
116
117 #[derive(Default)]
118 pub struct PersonQuery {
119   pub sort: Option<PersonSortType>,
120   pub search_term: Option<String>,
121   pub page: Option<i64>,
122   pub limit: Option<i64>,
123 }
124
125 impl PersonQuery {
126   pub async fn list(self, pool: &mut DbPool<'_>) -> Result<Vec<PersonView>, Error> {
127     queries().list(pool, ListMode::Query(self)).await
128   }
129 }
130
131 impl JoinView for PersonView {
132   type JoinTuple = PersonViewTuple;
133   fn from_tuple(a: Self::JoinTuple) -> Self {
134     Self {
135       person: a.0,
136       counts: a.1,
137     }
138   }
139 }