1 use crate::structs::CommunityModeratorView;
2 use diesel::{result::Error, ExpressionMethods, QueryDsl};
3 use diesel_async::RunQueryDsl;
5 newtypes::{CommunityId, PersonId},
6 schema::{community, community_moderator, person},
8 community::{Community, CommunitySafe},
9 person::{Person, PersonSafe},
11 traits::{ToSafe, ViewToVec},
12 utils::{get_conn, DbPool},
15 type CommunityModeratorViewTuple = (CommunitySafe, PersonSafe);
17 impl CommunityModeratorView {
18 pub async fn for_community(pool: &DbPool, community_id: CommunityId) -> Result<Vec<Self>, Error> {
19 let conn = &mut get_conn(pool).await?;
20 let res = community_moderator::table
21 .inner_join(community::table)
22 .inner_join(person::table)
24 Community::safe_columns_tuple(),
25 Person::safe_columns_tuple(),
27 .filter(community_moderator::community_id.eq(community_id))
28 .order_by(community_moderator::published)
29 .load::<CommunityModeratorViewTuple>(conn)
32 Ok(Self::from_tuple_to_vec(res))
35 pub async fn for_person(pool: &DbPool, person_id: PersonId) -> Result<Vec<Self>, Error> {
36 let conn = &mut get_conn(pool).await?;
37 let res = community_moderator::table
38 .inner_join(community::table)
39 .inner_join(person::table)
41 Community::safe_columns_tuple(),
42 Person::safe_columns_tuple(),
44 .filter(community_moderator::person_id.eq(person_id))
45 .filter(community::deleted.eq(false))
46 .filter(community::removed.eq(false))
47 .order_by(community_moderator::published)
48 .load::<CommunityModeratorViewTuple>(conn)
51 Ok(Self::from_tuple_to_vec(res))
54 /// Finds all communities first mods / creators
55 /// Ideally this should be a group by, but diesel doesn't support it yet
56 pub async fn get_community_first_mods(pool: &DbPool) -> Result<Vec<Self>, Error> {
57 let conn = &mut get_conn(pool).await?;
58 let res = community_moderator::table
59 .inner_join(community::table)
60 .inner_join(person::table)
62 Community::safe_columns_tuple(),
63 Person::safe_columns_tuple(),
65 // A hacky workaround instead of group_bys
66 // https://stackoverflow.com/questions/24042359/how-to-join-only-one-row-in-joined-table-with-postgres
67 .distinct_on(community_moderator::community_id)
69 community_moderator::community_id,
70 community_moderator::person_id,
72 .load::<CommunityModeratorViewTuple>(conn)
75 Ok(Self::from_tuple_to_vec(res))
79 impl ViewToVec for CommunityModeratorView {
80 type DbTuple = CommunityModeratorViewTuple;
81 fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
88 .collect::<Vec<Self>>()