]> Untitled Git - lemmy.git/blob - crates/db_schema/src/impls/comment.rs
Add diesel_async, get rid of blocking function (#2510)
[lemmy.git] / crates / db_schema / src / impls / comment.rs
1 use crate::{
2   newtypes::{CommentId, DbUrl, PersonId},
3   schema::comment::dsl::*,
4   source::comment::{
5     Comment,
6     CommentInsertForm,
7     CommentLike,
8     CommentLikeForm,
9     CommentSaved,
10     CommentSavedForm,
11     CommentUpdateForm,
12   },
13   traits::{Crud, DeleteableOrRemoveable, Likeable, Saveable},
14   utils::{get_conn, naive_now, DbPool},
15 };
16 use diesel::{dsl::*, result::Error, ExpressionMethods, QueryDsl};
17 use diesel_async::RunQueryDsl;
18 use diesel_ltree::Ltree;
19 use url::Url;
20
21 impl Comment {
22   pub async fn permadelete_for_creator(
23     pool: &DbPool,
24     for_creator_id: PersonId,
25   ) -> Result<Vec<Self>, Error> {
26     let conn = &mut get_conn(pool).await?;
27     diesel::update(comment.filter(creator_id.eq(for_creator_id)))
28       .set((
29         content.eq("*Permananently Deleted*"),
30         deleted.eq(true),
31         updated.eq(naive_now()),
32       ))
33       .get_results::<Self>(conn)
34       .await
35   }
36
37   pub async fn update_removed_for_creator(
38     pool: &DbPool,
39     for_creator_id: PersonId,
40     new_removed: bool,
41   ) -> Result<Vec<Self>, Error> {
42     let conn = &mut get_conn(pool).await?;
43     diesel::update(comment.filter(creator_id.eq(for_creator_id)))
44       .set((removed.eq(new_removed), updated.eq(naive_now())))
45       .get_results::<Self>(conn)
46       .await
47   }
48
49   pub async fn create(
50     pool: &DbPool,
51     comment_form: &CommentInsertForm,
52     parent_path: Option<&Ltree>,
53   ) -> Result<Comment, Error> {
54     let conn = &mut get_conn(pool).await?;
55
56     // Insert, to get the id
57     let inserted_comment = insert_into(comment)
58       .values(comment_form)
59       .on_conflict(ap_id)
60       .do_update()
61       .set(comment_form)
62       .get_result::<Self>(conn)
63       .await;
64
65     if let Ok(comment_insert) = inserted_comment {
66       let comment_id = comment_insert.id;
67
68       // You need to update the ltree column
69       let ltree = Ltree(if let Some(parent_path) = parent_path {
70         // The previous parent will already have 0 in it
71         // Append this comment id
72         format!("{}.{}", parent_path.0, comment_id)
73       } else {
74         // '0' is always the first path, append to that
75         format!("{}.{}", 0, comment_id)
76       });
77
78       let updated_comment = diesel::update(comment.find(comment_id))
79         .set(path.eq(ltree))
80         .get_result::<Self>(conn)
81         .await;
82
83       // Update the child count for the parent comment_aggregates
84       // You could do this with a trigger, but since you have to do this manually anyway,
85       // you can just have it here
86       if let Some(parent_path) = parent_path {
87         // You have to update counts for all parents, not just the immediate one
88         // TODO if the performance of this is terrible, it might be better to do this as part of a
89         // scheduled query... although the counts would often be wrong.
90         //
91         // The child_count query for reference:
92         // select c.id, c.path, count(c2.id) as child_count from comment c
93         // left join comment c2 on c2.path <@ c.path and c2.path != c.path
94         // group by c.id
95
96         let top_parent = format!("0.{}", parent_path.0.split('.').collect::<Vec<&str>>()[1]);
97         let update_child_count_stmt = format!(
98           "
99 update comment_aggregates ca set child_count = c.child_count
100 from (
101   select c.id, c.path, count(c2.id) as child_count from comment c
102   join comment c2 on c2.path <@ c.path and c2.path != c.path
103   and c.path <@ '{}'
104   group by c.id
105 ) as c
106 where ca.comment_id = c.id",
107           top_parent
108         );
109
110         sql_query(update_child_count_stmt).execute(conn).await?;
111       }
112       updated_comment
113     } else {
114       inserted_comment
115     }
116   }
117   pub async fn read_from_apub_id(pool: &DbPool, object_id: Url) -> Result<Option<Self>, Error> {
118     let conn = &mut get_conn(pool).await?;
119     let object_id: DbUrl = object_id.into();
120     Ok(
121       comment
122         .filter(ap_id.eq(object_id))
123         .first::<Comment>(conn)
124         .await
125         .ok()
126         .map(Into::into),
127     )
128   }
129
130   pub fn parent_comment_id(&self) -> Option<CommentId> {
131     let mut ltree_split: Vec<&str> = self.path.0.split('.').collect();
132     ltree_split.remove(0); // The first is always 0
133     if ltree_split.len() > 1 {
134       ltree_split[ltree_split.len() - 2]
135         .parse::<i32>()
136         .map(CommentId)
137         .ok()
138     } else {
139       None
140     }
141   }
142 }
143
144 #[async_trait]
145 impl Crud for Comment {
146   type InsertForm = CommentInsertForm;
147   type UpdateForm = CommentUpdateForm;
148   type IdType = CommentId;
149   async fn read(pool: &DbPool, comment_id: CommentId) -> Result<Self, Error> {
150     let conn = &mut get_conn(pool).await?;
151     comment.find(comment_id).first::<Self>(conn).await
152   }
153
154   async fn delete(pool: &DbPool, comment_id: CommentId) -> Result<usize, Error> {
155     let conn = &mut get_conn(pool).await?;
156     diesel::delete(comment.find(comment_id)).execute(conn).await
157   }
158
159   /// This is unimplemented, use [[Comment::create]]
160   async fn create(_pool: &DbPool, _comment_form: &Self::InsertForm) -> Result<Self, Error> {
161     unimplemented!();
162   }
163
164   async fn update(
165     pool: &DbPool,
166     comment_id: CommentId,
167     comment_form: &Self::UpdateForm,
168   ) -> Result<Self, Error> {
169     let conn = &mut get_conn(pool).await?;
170     diesel::update(comment.find(comment_id))
171       .set(comment_form)
172       .get_result::<Self>(conn)
173       .await
174   }
175 }
176
177 #[async_trait]
178 impl Likeable for CommentLike {
179   type Form = CommentLikeForm;
180   type IdType = CommentId;
181   async fn like(pool: &DbPool, comment_like_form: &CommentLikeForm) -> Result<Self, Error> {
182     use crate::schema::comment_like::dsl::*;
183     let conn = &mut get_conn(pool).await?;
184     insert_into(comment_like)
185       .values(comment_like_form)
186       .on_conflict((comment_id, person_id))
187       .do_update()
188       .set(comment_like_form)
189       .get_result::<Self>(conn)
190       .await
191   }
192   async fn remove(
193     pool: &DbPool,
194     person_id_: PersonId,
195     comment_id_: CommentId,
196   ) -> Result<usize, Error> {
197     use crate::schema::comment_like::dsl::*;
198     let conn = &mut get_conn(pool).await?;
199     diesel::delete(
200       comment_like
201         .filter(comment_id.eq(comment_id_))
202         .filter(person_id.eq(person_id_)),
203     )
204     .execute(conn)
205     .await
206   }
207 }
208
209 #[async_trait]
210 impl Saveable for CommentSaved {
211   type Form = CommentSavedForm;
212   async fn save(pool: &DbPool, comment_saved_form: &CommentSavedForm) -> Result<Self, Error> {
213     use crate::schema::comment_saved::dsl::*;
214     let conn = &mut get_conn(pool).await?;
215     insert_into(comment_saved)
216       .values(comment_saved_form)
217       .on_conflict((comment_id, person_id))
218       .do_update()
219       .set(comment_saved_form)
220       .get_result::<Self>(conn)
221       .await
222   }
223   async fn unsave(pool: &DbPool, comment_saved_form: &CommentSavedForm) -> Result<usize, Error> {
224     use crate::schema::comment_saved::dsl::*;
225     let conn = &mut get_conn(pool).await?;
226     diesel::delete(
227       comment_saved
228         .filter(comment_id.eq(comment_saved_form.comment_id))
229         .filter(person_id.eq(comment_saved_form.person_id)),
230     )
231     .execute(conn)
232     .await
233   }
234 }
235
236 impl DeleteableOrRemoveable for Comment {
237   fn blank_out_deleted_or_removed_info(mut self) -> Self {
238     self.content = "".into();
239     self
240   }
241 }
242
243 #[cfg(test)]
244 mod tests {
245   use crate::{
246     newtypes::LanguageId,
247     source::{
248       comment::*,
249       community::{Community, CommunityInsertForm},
250       instance::Instance,
251       person::{Person, PersonInsertForm},
252       post::*,
253     },
254     traits::{Crud, Likeable, Saveable},
255     utils::build_db_pool_for_tests,
256   };
257   use diesel_ltree::Ltree;
258   use serial_test::serial;
259
260   #[tokio::test]
261   #[serial]
262   async fn test_crud() {
263     let pool = &build_db_pool_for_tests().await;
264
265     let inserted_instance = Instance::create(pool, "my_domain.tld").await.unwrap();
266
267     let new_person = PersonInsertForm::builder()
268       .name("terry".into())
269       .public_key("pubkey".to_string())
270       .instance_id(inserted_instance.id)
271       .build();
272
273     let inserted_person = Person::create(pool, &new_person).await.unwrap();
274
275     let new_community = CommunityInsertForm::builder()
276       .name("test community".to_string())
277       .title("nada".to_owned())
278       .public_key("pubkey".to_string())
279       .instance_id(inserted_instance.id)
280       .build();
281
282     let inserted_community = Community::create(pool, &new_community).await.unwrap();
283
284     let new_post = PostInsertForm::builder()
285       .name("A test post".into())
286       .creator_id(inserted_person.id)
287       .community_id(inserted_community.id)
288       .build();
289
290     let inserted_post = Post::create(pool, &new_post).await.unwrap();
291
292     let comment_form = CommentInsertForm::builder()
293       .content("A test comment".into())
294       .creator_id(inserted_person.id)
295       .post_id(inserted_post.id)
296       .build();
297
298     let inserted_comment = Comment::create(pool, &comment_form, None).await.unwrap();
299
300     let expected_comment = Comment {
301       id: inserted_comment.id,
302       content: "A test comment".into(),
303       creator_id: inserted_person.id,
304       post_id: inserted_post.id,
305       removed: false,
306       deleted: false,
307       path: Ltree(format!("0.{}", inserted_comment.id)),
308       published: inserted_comment.published,
309       updated: None,
310       ap_id: inserted_comment.ap_id.to_owned(),
311       distinguished: false,
312       local: true,
313       language_id: LanguageId::default(),
314     };
315
316     let child_comment_form = CommentInsertForm::builder()
317       .content("A child comment".into())
318       .creator_id(inserted_person.id)
319       .post_id(inserted_post.id)
320       .build();
321
322     let inserted_child_comment =
323       Comment::create(pool, &child_comment_form, Some(&inserted_comment.path))
324         .await
325         .unwrap();
326
327     // Comment Like
328     let comment_like_form = CommentLikeForm {
329       comment_id: inserted_comment.id,
330       post_id: inserted_post.id,
331       person_id: inserted_person.id,
332       score: 1,
333     };
334
335     let inserted_comment_like = CommentLike::like(pool, &comment_like_form).await.unwrap();
336
337     let expected_comment_like = CommentLike {
338       id: inserted_comment_like.id,
339       comment_id: inserted_comment.id,
340       post_id: inserted_post.id,
341       person_id: inserted_person.id,
342       published: inserted_comment_like.published,
343       score: 1,
344     };
345
346     // Comment Saved
347     let comment_saved_form = CommentSavedForm {
348       comment_id: inserted_comment.id,
349       person_id: inserted_person.id,
350     };
351
352     let inserted_comment_saved = CommentSaved::save(pool, &comment_saved_form).await.unwrap();
353
354     let expected_comment_saved = CommentSaved {
355       id: inserted_comment_saved.id,
356       comment_id: inserted_comment.id,
357       person_id: inserted_person.id,
358       published: inserted_comment_saved.published,
359     };
360
361     let comment_update_form = CommentUpdateForm::builder()
362       .content(Some("A test comment".into()))
363       .build();
364
365     let updated_comment = Comment::update(pool, inserted_comment.id, &comment_update_form)
366       .await
367       .unwrap();
368
369     let read_comment = Comment::read(pool, inserted_comment.id).await.unwrap();
370     let like_removed = CommentLike::remove(pool, inserted_person.id, inserted_comment.id)
371       .await
372       .unwrap();
373     let saved_removed = CommentSaved::unsave(pool, &comment_saved_form)
374       .await
375       .unwrap();
376     let num_deleted = Comment::delete(pool, inserted_comment.id).await.unwrap();
377     Comment::delete(pool, inserted_child_comment.id)
378       .await
379       .unwrap();
380     Post::delete(pool, inserted_post.id).await.unwrap();
381     Community::delete(pool, inserted_community.id)
382       .await
383       .unwrap();
384     Person::delete(pool, inserted_person.id).await.unwrap();
385     Instance::delete(pool, inserted_instance.id).await.unwrap();
386
387     assert_eq!(expected_comment, read_comment);
388     assert_eq!(expected_comment, inserted_comment);
389     assert_eq!(expected_comment, updated_comment);
390     assert_eq!(expected_comment_like, inserted_comment_like);
391     assert_eq!(expected_comment_saved, inserted_comment_saved);
392     assert_eq!(
393       format!("0.{}.{}", expected_comment.id, inserted_child_comment.id),
394       inserted_child_comment.path.0,
395     );
396     assert_eq!(1, like_removed);
397     assert_eq!(1, saved_removed);
398     assert_eq!(1, num_deleted);
399   }
400 }