1 use crate::structs::CommunityModeratorView;
2 use diesel::{result::Error, *};
4 newtypes::{CommunityId, PersonId},
5 schema::{community, community_moderator, person},
7 community::{Community, CommunitySafe},
8 person::{Person, PersonSafe},
10 traits::{ToSafe, ViewToVec},
13 type CommunityModeratorViewTuple = (CommunitySafe, PersonSafe);
15 impl CommunityModeratorView {
16 pub fn for_community(conn: &PgConnection, community_id: CommunityId) -> Result<Vec<Self>, Error> {
17 let res = community_moderator::table
18 .inner_join(community::table)
19 .inner_join(person::table)
21 Community::safe_columns_tuple(),
22 Person::safe_columns_tuple(),
24 .filter(community_moderator::community_id.eq(community_id))
25 .order_by(community_moderator::published)
26 .load::<CommunityModeratorViewTuple>(conn)?;
28 Ok(Self::from_tuple_to_vec(res))
31 pub fn for_person(conn: &PgConnection, person_id: PersonId) -> Result<Vec<Self>, Error> {
32 let res = community_moderator::table
33 .inner_join(community::table)
34 .inner_join(person::table)
36 Community::safe_columns_tuple(),
37 Person::safe_columns_tuple(),
39 .filter(community_moderator::person_id.eq(person_id))
40 .order_by(community_moderator::published)
41 .load::<CommunityModeratorViewTuple>(conn)?;
43 Ok(Self::from_tuple_to_vec(res))
46 /// Finds all communities first mods / creators
47 /// Ideally this should be a group by, but diesel doesn't support it yet
48 pub fn get_community_first_mods(conn: &PgConnection) -> Result<Vec<Self>, Error> {
49 let res = community_moderator::table
50 .inner_join(community::table)
51 .inner_join(person::table)
53 Community::safe_columns_tuple(),
54 Person::safe_columns_tuple(),
56 // A hacky workaround instead of group_bys
57 // https://stackoverflow.com/questions/24042359/how-to-join-only-one-row-in-joined-table-with-postgres
58 .distinct_on(community_moderator::community_id)
60 community_moderator::community_id,
61 community_moderator::person_id,
63 .load::<CommunityModeratorViewTuple>(conn)?;
65 Ok(Self::from_tuple_to_vec(res))
69 impl ViewToVec for CommunityModeratorView {
70 type DbTuple = CommunityModeratorViewTuple;
71 fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
75 community: a.0.to_owned(),
76 moderator: a.1.to_owned(),
78 .collect::<Vec<Self>>()