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(
16 pool: &mut DbPool<'_>,
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(
35 pool: &mut DbPool<'_>,
36 community_id: CommunityId,
37 ) -> Result<Vec<Self>, Error> {
38 let conn = &mut get_conn(pool).await?;
39 let res = community_moderator::table
40 .inner_join(community::table)
41 .inner_join(person::table)
42 .filter(community_moderator::community_id.eq(community_id))
43 .select((community::all_columns, person::all_columns))
44 .order_by(community_moderator::published)
45 .load::<CommunityModeratorViewTuple>(conn)
48 Ok(res.into_iter().map(Self::from_tuple).collect())
51 pub async fn for_person(pool: &mut DbPool<'_>, person_id: PersonId) -> Result<Vec<Self>, Error> {
52 let conn = &mut get_conn(pool).await?;
53 let res = community_moderator::table
54 .inner_join(community::table)
55 .inner_join(person::table)
56 .filter(community_moderator::person_id.eq(person_id))
57 .filter(community::deleted.eq(false))
58 .filter(community::removed.eq(false))
59 .select((community::all_columns, person::all_columns))
60 .load::<CommunityModeratorViewTuple>(conn)
63 Ok(res.into_iter().map(Self::from_tuple).collect())
66 /// Finds all communities first mods / creators
67 /// Ideally this should be a group by, but diesel doesn't support it yet
68 pub async fn get_community_first_mods(pool: &mut DbPool<'_>) -> Result<Vec<Self>, Error> {
69 let conn = &mut get_conn(pool).await?;
70 let res = community_moderator::table
71 .inner_join(community::table)
72 .inner_join(person::table)
73 .select((community::all_columns, person::all_columns))
74 // A hacky workaround instead of group_bys
75 // https://stackoverflow.com/questions/24042359/how-to-join-only-one-row-in-joined-table-with-postgres
76 .distinct_on(community_moderator::community_id)
78 community_moderator::community_id,
79 community_moderator::person_id,
81 .load::<CommunityModeratorViewTuple>(conn)
84 Ok(res.into_iter().map(Self::from_tuple).collect())
88 impl JoinView for CommunityModeratorView {
89 type JoinTuple = CommunityModeratorViewTuple;
90 fn from_tuple(a: Self::JoinTuple) -> Self {