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