]> Untitled Git - lemmy.git/blob - crates/db_schema/src/impls/person_block.rs
Make functions work with both connection and pool (#3420)
[lemmy.git] / crates / db_schema / src / impls / person_block.rs
1 use crate::{
2   newtypes::PersonId,
3   schema::person_block::dsl::{person_block, person_id, target_id},
4   source::person_block::{PersonBlock, PersonBlockForm},
5   traits::Blockable,
6   utils::{get_conn, DbPool},
7 };
8 use diesel::{dsl::insert_into, result::Error, ExpressionMethods, QueryDsl};
9 use diesel_async::RunQueryDsl;
10
11 impl PersonBlock {
12   pub async fn read(
13     pool: &mut DbPool<'_>,
14     for_person_id: PersonId,
15     for_recipient_id: PersonId,
16   ) -> Result<Self, Error> {
17     let conn = &mut get_conn(pool).await?;
18     person_block
19       .filter(person_id.eq(for_person_id))
20       .filter(target_id.eq(for_recipient_id))
21       .first::<Self>(conn)
22       .await
23   }
24 }
25
26 #[async_trait]
27 impl Blockable for PersonBlock {
28   type Form = PersonBlockForm;
29   async fn block(
30     pool: &mut DbPool<'_>,
31     person_block_form: &PersonBlockForm,
32   ) -> Result<Self, Error> {
33     let conn = &mut get_conn(pool).await?;
34     insert_into(person_block)
35       .values(person_block_form)
36       .on_conflict((person_id, target_id))
37       .do_update()
38       .set(person_block_form)
39       .get_result::<Self>(conn)
40       .await
41   }
42   async fn unblock(pool: &mut DbPool<'_>, person_block_form: &Self::Form) -> Result<usize, Error> {
43     let conn = &mut get_conn(pool).await?;
44     diesel::delete(
45       person_block
46         .filter(person_id.eq(person_block_form.person_id))
47         .filter(target_id.eq(person_block_form.target_id)),
48     )
49     .execute(conn)
50     .await
51   }
52 }