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