]> Untitled Git - lemmy.git/blob - crates/db_schema/src/impls/tagline.rs
Make functions work with both connection and pool (#3420)
[lemmy.git] / crates / db_schema / src / impls / tagline.rs
1 use crate::{
2   newtypes::LocalSiteId,
3   schema::tagline::dsl::{local_site_id, tagline},
4   source::tagline::{Tagline, TaglineForm},
5   utils::{get_conn, DbPool},
6 };
7 use diesel::{insert_into, result::Error, ExpressionMethods, QueryDsl};
8 use diesel_async::{AsyncPgConnection, RunQueryDsl};
9
10 impl Tagline {
11   pub async fn replace(
12     pool: &mut DbPool<'_>,
13     for_local_site_id: LocalSiteId,
14     list_content: Option<Vec<String>>,
15   ) -> Result<Vec<Self>, Error> {
16     let conn = &mut get_conn(pool).await?;
17     if let Some(list) = list_content {
18       conn
19         .build_transaction()
20         .run(|conn| {
21           Box::pin(async move {
22             Self::clear(conn).await?;
23
24             for item in list {
25               let form = TaglineForm {
26                 local_site_id: for_local_site_id,
27                 content: item,
28                 updated: None,
29               };
30               insert_into(tagline)
31                 .values(form)
32                 .get_result::<Self>(conn)
33                 .await?;
34             }
35             Self::get_all(&mut conn.into(), for_local_site_id).await
36           }) as _
37         })
38         .await
39     } else {
40       Self::get_all(&mut conn.into(), for_local_site_id).await
41     }
42   }
43
44   async fn clear(conn: &mut AsyncPgConnection) -> Result<usize, Error> {
45     diesel::delete(tagline).execute(conn).await
46   }
47
48   pub async fn get_all(
49     pool: &mut DbPool<'_>,
50     for_local_site_id: LocalSiteId,
51   ) -> Result<Vec<Self>, Error> {
52     let conn = &mut get_conn(pool).await?;
53     tagline
54       .filter(local_site_id.eq(for_local_site_id))
55       .get_results::<Self>(conn)
56       .await
57   }
58 }