1 use diesel::{result::Error, *};
2 use lemmy_db_queries::{ToSafe, ViewToVec};
4 schema::{community, community_moderator, person},
6 community::{Community, CommunitySafe},
7 person::{Person, PersonSafe},
14 #[derive(Debug, Serialize, Clone)]
15 pub struct CommunityModeratorView {
16 pub community: CommunitySafe,
17 pub moderator: PersonSafe,
20 type CommunityModeratorViewTuple = (CommunitySafe, PersonSafe);
22 impl CommunityModeratorView {
23 pub fn for_community(conn: &PgConnection, community_id: CommunityId) -> Result<Vec<Self>, Error> {
24 let res = community_moderator::table
25 .inner_join(community::table)
26 .inner_join(person::table)
28 Community::safe_columns_tuple(),
29 Person::safe_columns_tuple(),
31 .filter(community_moderator::community_id.eq(community_id))
32 .order_by(community_moderator::published)
33 .load::<CommunityModeratorViewTuple>(conn)?;
35 Ok(Self::from_tuple_to_vec(res))
38 pub fn for_person(conn: &PgConnection, person_id: PersonId) -> Result<Vec<Self>, Error> {
39 let res = community_moderator::table
40 .inner_join(community::table)
41 .inner_join(person::table)
43 Community::safe_columns_tuple(),
44 Person::safe_columns_tuple(),
46 .filter(community_moderator::person_id.eq(person_id))
47 .order_by(community_moderator::published)
48 .load::<CommunityModeratorViewTuple>(conn)?;
50 Ok(Self::from_tuple_to_vec(res))
53 /// Finds all communities first mods / creators
54 /// Ideally this should be a group by, but diesel doesn't support it yet
55 pub fn get_community_first_mods(conn: &PgConnection) -> Result<Vec<Self>, Error> {
56 let res = community_moderator::table
57 .inner_join(community::table)
58 .inner_join(person::table)
60 Community::safe_columns_tuple(),
61 Person::safe_columns_tuple(),
63 // A hacky workaround instead of group_bys
64 // https://stackoverflow.com/questions/24042359/how-to-join-only-one-row-in-joined-table-with-postgres
65 .distinct_on(community_moderator::community_id)
67 community_moderator::community_id,
68 community_moderator::person_id,
70 .load::<CommunityModeratorViewTuple>(conn)?;
72 Ok(Self::from_tuple_to_vec(res))
76 impl ViewToVec for CommunityModeratorView {
77 type DbTuple = CommunityModeratorViewTuple;
78 fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
82 community: a.0.to_owned(),
83 moderator: a.1.to_owned(),
85 .collect::<Vec<Self>>()