1 use crate::structs::CommunityModeratorView;
2 use diesel::{dsl::exists, result::Error, select, ExpressionMethods, QueryDsl};
3 use diesel_async::RunQueryDsl;
5 newtypes::{CommunityId, PersonId},
6 schema::{community, community_moderator, person},
7 source::{community::Community, person::Person},
9 utils::{get_conn, DbPool},
12 type CommunityModeratorViewTuple = (Community, Person);
14 impl CommunityModeratorView {
15 pub async fn is_community_moderator(
17 find_community_id: CommunityId,
18 find_person_id: PersonId,
19 ) -> Result<bool, Error> {
20 use lemmy_db_schema::schema::community_moderator::dsl::{
25 let conn = &mut get_conn(pool).await?;
28 .filter(community_id.eq(find_community_id))
29 .filter(person_id.eq(find_person_id)),
31 .get_result::<bool>(conn)
34 pub async fn for_community(pool: &DbPool, community_id: CommunityId) -> Result<Vec<Self>, Error> {
35 let conn = &mut get_conn(pool).await?;
36 let res = community_moderator::table
37 .inner_join(community::table)
38 .inner_join(person::table)
39 .filter(community_moderator::community_id.eq(community_id))
40 .select((community::all_columns, person::all_columns))
41 .order_by(community_moderator::published)
42 .load::<CommunityModeratorViewTuple>(conn)
45 Ok(res.into_iter().map(Self::from_tuple).collect())
48 pub async fn for_person(pool: &DbPool, person_id: PersonId) -> Result<Vec<Self>, Error> {
49 let conn = &mut get_conn(pool).await?;
50 let res = community_moderator::table
51 .inner_join(community::table)
52 .inner_join(person::table)
53 .filter(community_moderator::person_id.eq(person_id))
54 .filter(community::deleted.eq(false))
55 .filter(community::removed.eq(false))
56 .select((community::all_columns, person::all_columns))
57 .load::<CommunityModeratorViewTuple>(conn)
60 Ok(res.into_iter().map(Self::from_tuple).collect())
63 /// Finds all communities first mods / creators
64 /// Ideally this should be a group by, but diesel doesn't support it yet
65 pub async fn get_community_first_mods(pool: &DbPool) -> Result<Vec<Self>, Error> {
66 let conn = &mut get_conn(pool).await?;
67 let res = community_moderator::table
68 .inner_join(community::table)
69 .inner_join(person::table)
70 .select((community::all_columns, person::all_columns))
71 // A hacky workaround instead of group_bys
72 // https://stackoverflow.com/questions/24042359/how-to-join-only-one-row-in-joined-table-with-postgres
73 .distinct_on(community_moderator::community_id)
75 community_moderator::community_id,
76 community_moderator::person_id,
78 .load::<CommunityModeratorViewTuple>(conn)
81 Ok(res.into_iter().map(Self::from_tuple).collect())
85 impl JoinView for CommunityModeratorView {
86 type JoinTuple = CommunityModeratorViewTuple;
87 fn from_tuple(a: Self::JoinTuple) -> Self {