]> Untitled Git - lemmy.git/blob - crates/db_schema/src/aggregates/person_post_aggregates.rs
Make functions work with both connection and pool (#3420)
[lemmy.git] / crates / db_schema / src / aggregates / person_post_aggregates.rs
1 use crate::{
2   aggregates::structs::{PersonPostAggregates, PersonPostAggregatesForm},
3   diesel::BoolExpressionMethods,
4   newtypes::{PersonId, PostId},
5   schema::person_post_aggregates::dsl::{person_id, person_post_aggregates, post_id},
6   utils::{get_conn, DbPool},
7 };
8 use diesel::{insert_into, result::Error, ExpressionMethods, QueryDsl};
9 use diesel_async::RunQueryDsl;
10
11 impl PersonPostAggregates {
12   pub async fn upsert(
13     pool: &mut DbPool<'_>,
14     form: &PersonPostAggregatesForm,
15   ) -> Result<Self, Error> {
16     let conn = &mut get_conn(pool).await?;
17     insert_into(person_post_aggregates)
18       .values(form)
19       .on_conflict((person_id, post_id))
20       .do_update()
21       .set(form)
22       .get_result::<Self>(conn)
23       .await
24   }
25   pub async fn read(
26     pool: &mut DbPool<'_>,
27     person_id_: PersonId,
28     post_id_: PostId,
29   ) -> Result<Self, Error> {
30     let conn = &mut get_conn(pool).await?;
31     person_post_aggregates
32       .filter(post_id.eq(post_id_).and(person_id.eq(person_id_)))
33       .first::<Self>(conn)
34       .await
35   }
36 }