]> Untitled Git - lemmy.git/blob - crates/db_views_actor/src/community_follower_view.rs
Make functions work with both connection and pool (#3420)
[lemmy.git] / crates / db_views_actor / src / community_follower_view.rs
1 use crate::structs::CommunityFollowerView;
2 use diesel::{
3   dsl::{count_star, not},
4   result::Error,
5   sql_function,
6   ExpressionMethods,
7   QueryDsl,
8 };
9 use diesel_async::RunQueryDsl;
10 use lemmy_db_schema::{
11   newtypes::{CommunityId, DbUrl, PersonId},
12   schema::{community, community_follower, person},
13   source::{community::Community, person::Person},
14   traits::JoinView,
15   utils::{get_conn, DbPool},
16 };
17
18 type CommunityFollowerViewTuple = (Community, Person);
19
20 sql_function!(fn coalesce(x: diesel::sql_types::Nullable<diesel::sql_types::Text>, y: diesel::sql_types::Text) -> diesel::sql_types::Text);
21
22 impl CommunityFollowerView {
23   pub async fn get_community_follower_inboxes(
24     pool: &mut DbPool<'_>,
25     community_id: CommunityId,
26   ) -> Result<Vec<DbUrl>, Error> {
27     let conn = &mut get_conn(pool).await?;
28     let res = community_follower::table
29       .filter(community_follower::community_id.eq(community_id))
30       .filter(not(person::local))
31       .inner_join(person::table)
32       .select(coalesce(person::shared_inbox_url, person::inbox_url))
33       .distinct()
34       .load::<DbUrl>(conn)
35       .await?;
36
37     Ok(res)
38   }
39   pub async fn count_community_followers(
40     pool: &mut DbPool<'_>,
41     community_id: CommunityId,
42   ) -> Result<i64, Error> {
43     let conn = &mut get_conn(pool).await?;
44     let res = community_follower::table
45       .filter(community_follower::community_id.eq(community_id))
46       .select(count_star())
47       .first::<i64>(conn)
48       .await?;
49
50     Ok(res)
51   }
52
53   pub async fn for_person(pool: &mut DbPool<'_>, person_id: PersonId) -> Result<Vec<Self>, Error> {
54     let conn = &mut get_conn(pool).await?;
55     let res = community_follower::table
56       .inner_join(community::table)
57       .inner_join(person::table)
58       .select((community::all_columns, person::all_columns))
59       .filter(community_follower::person_id.eq(person_id))
60       .filter(community::deleted.eq(false))
61       .filter(community::removed.eq(false))
62       .order_by(community::title)
63       .load::<CommunityFollowerViewTuple>(conn)
64       .await?;
65
66     Ok(res.into_iter().map(Self::from_tuple).collect())
67   }
68 }
69
70 impl JoinView for CommunityFollowerView {
71   type JoinTuple = CommunityFollowerViewTuple;
72   fn from_tuple(a: Self::JoinTuple) -> Self {
73     Self {
74       community: a.0,
75       follower: a.1,
76     }
77   }
78 }