]> Untitled Git - lemmy.git/blob - crates/db_schema/src/impls/comment.rs
2b5b74a1a12f135f8b8c72d2de2e35384857d08b
[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: &mut 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: &mut 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: &mut 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(
127     pool: &mut DbPool<'_>,
128     object_id: Url,
129   ) -> Result<Option<Self>, Error> {
130     let conn = &mut get_conn(pool).await?;
131     let object_id: DbUrl = object_id.into();
132     Ok(
133       comment
134         .filter(ap_id.eq(object_id))
135         .first::<Comment>(conn)
136         .await
137         .ok()
138         .map(Into::into),
139     )
140   }
141
142   pub fn parent_comment_id(&self) -> Option<CommentId> {
143     let mut ltree_split: Vec<&str> = self.path.0.split('.').collect();
144     ltree_split.remove(0); // The first is always 0
145     if ltree_split.len() > 1 {
146       let parent_comment_id = ltree_split.get(ltree_split.len() - 2);
147       parent_comment_id.and_then(|p| p.parse::<i32>().map(CommentId).ok())
148     } else {
149       None
150     }
151   }
152 }
153
154 #[async_trait]
155 impl Crud for Comment {
156   type InsertForm = CommentInsertForm;
157   type UpdateForm = CommentUpdateForm;
158   type IdType = CommentId;
159   async fn read(pool: &mut DbPool<'_>, comment_id: CommentId) -> Result<Self, Error> {
160     let conn = &mut get_conn(pool).await?;
161     comment.find(comment_id).first::<Self>(conn).await
162   }
163
164   async fn delete(pool: &mut DbPool<'_>, comment_id: CommentId) -> Result<usize, Error> {
165     let conn = &mut get_conn(pool).await?;
166     diesel::delete(comment.find(comment_id)).execute(conn).await
167   }
168
169   /// This is unimplemented, use [[Comment::create]]
170   async fn create(_pool: &mut DbPool<'_>, _comment_form: &Self::InsertForm) -> Result<Self, Error> {
171     unimplemented!();
172   }
173
174   async fn update(
175     pool: &mut DbPool<'_>,
176     comment_id: CommentId,
177     comment_form: &Self::UpdateForm,
178   ) -> Result<Self, Error> {
179     let conn = &mut get_conn(pool).await?;
180     diesel::update(comment.find(comment_id))
181       .set(comment_form)
182       .get_result::<Self>(conn)
183       .await
184   }
185 }
186
187 #[async_trait]
188 impl Likeable for CommentLike {
189   type Form = CommentLikeForm;
190   type IdType = CommentId;
191   async fn like(pool: &mut DbPool<'_>, comment_like_form: &CommentLikeForm) -> Result<Self, Error> {
192     use crate::schema::comment_like::dsl::{comment_id, comment_like, person_id};
193     let conn = &mut get_conn(pool).await?;
194     insert_into(comment_like)
195       .values(comment_like_form)
196       .on_conflict((comment_id, person_id))
197       .do_update()
198       .set(comment_like_form)
199       .get_result::<Self>(conn)
200       .await
201   }
202   async fn remove(
203     pool: &mut DbPool<'_>,
204     person_id_: PersonId,
205     comment_id_: CommentId,
206   ) -> Result<usize, Error> {
207     use crate::schema::comment_like::dsl::{comment_id, comment_like, person_id};
208     let conn = &mut get_conn(pool).await?;
209     diesel::delete(
210       comment_like
211         .filter(comment_id.eq(comment_id_))
212         .filter(person_id.eq(person_id_)),
213     )
214     .execute(conn)
215     .await
216   }
217 }
218
219 #[async_trait]
220 impl Saveable for CommentSaved {
221   type Form = CommentSavedForm;
222   async fn save(
223     pool: &mut DbPool<'_>,
224     comment_saved_form: &CommentSavedForm,
225   ) -> Result<Self, Error> {
226     use crate::schema::comment_saved::dsl::{comment_id, comment_saved, person_id};
227     let conn = &mut get_conn(pool).await?;
228     insert_into(comment_saved)
229       .values(comment_saved_form)
230       .on_conflict((comment_id, person_id))
231       .do_update()
232       .set(comment_saved_form)
233       .get_result::<Self>(conn)
234       .await
235   }
236   async fn unsave(
237     pool: &mut DbPool<'_>,
238     comment_saved_form: &CommentSavedForm,
239   ) -> Result<usize, Error> {
240     use crate::schema::comment_saved::dsl::{comment_id, comment_saved, person_id};
241     let conn = &mut get_conn(pool).await?;
242     diesel::delete(
243       comment_saved
244         .filter(comment_id.eq(comment_saved_form.comment_id))
245         .filter(person_id.eq(comment_saved_form.person_id)),
246     )
247     .execute(conn)
248     .await
249   }
250 }
251
252 #[cfg(test)]
253 mod tests {
254   use crate::{
255     newtypes::LanguageId,
256     source::{
257       comment::{
258         Comment,
259         CommentInsertForm,
260         CommentLike,
261         CommentLikeForm,
262         CommentSaved,
263         CommentSavedForm,
264         CommentUpdateForm,
265       },
266       community::{Community, CommunityInsertForm},
267       instance::Instance,
268       person::{Person, PersonInsertForm},
269       post::{Post, PostInsertForm},
270     },
271     traits::{Crud, Likeable, Saveable},
272     utils::build_db_pool_for_tests,
273   };
274   use diesel_ltree::Ltree;
275   use serial_test::serial;
276
277   #[tokio::test]
278   #[serial]
279   async fn test_crud() {
280     let pool = &build_db_pool_for_tests().await;
281     let pool = &mut pool.into();
282
283     let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string())
284       .await
285       .unwrap();
286
287     let new_person = PersonInsertForm::builder()
288       .name("terry".into())
289       .public_key("pubkey".to_string())
290       .instance_id(inserted_instance.id)
291       .build();
292
293     let inserted_person = Person::create(pool, &new_person).await.unwrap();
294
295     let new_community = CommunityInsertForm::builder()
296       .name("test community".to_string())
297       .title("nada".to_owned())
298       .public_key("pubkey".to_string())
299       .instance_id(inserted_instance.id)
300       .build();
301
302     let inserted_community = Community::create(pool, &new_community).await.unwrap();
303
304     let new_post = PostInsertForm::builder()
305       .name("A test post".into())
306       .creator_id(inserted_person.id)
307       .community_id(inserted_community.id)
308       .build();
309
310     let inserted_post = Post::create(pool, &new_post).await.unwrap();
311
312     let comment_form = CommentInsertForm::builder()
313       .content("A test comment".into())
314       .creator_id(inserted_person.id)
315       .post_id(inserted_post.id)
316       .build();
317
318     let inserted_comment = Comment::create(pool, &comment_form, None).await.unwrap();
319
320     let expected_comment = Comment {
321       id: inserted_comment.id,
322       content: "A test comment".into(),
323       creator_id: inserted_person.id,
324       post_id: inserted_post.id,
325       removed: false,
326       deleted: false,
327       path: Ltree(format!("0.{}", inserted_comment.id)),
328       published: inserted_comment.published,
329       updated: None,
330       ap_id: inserted_comment.ap_id.clone(),
331       distinguished: false,
332       local: true,
333       language_id: LanguageId::default(),
334     };
335
336     let child_comment_form = CommentInsertForm::builder()
337       .content("A child comment".into())
338       .creator_id(inserted_person.id)
339       .post_id(inserted_post.id)
340       .build();
341
342     let inserted_child_comment =
343       Comment::create(pool, &child_comment_form, Some(&inserted_comment.path))
344         .await
345         .unwrap();
346
347     // Comment Like
348     let comment_like_form = CommentLikeForm {
349       comment_id: inserted_comment.id,
350       post_id: inserted_post.id,
351       person_id: inserted_person.id,
352       score: 1,
353     };
354
355     let inserted_comment_like = CommentLike::like(pool, &comment_like_form).await.unwrap();
356
357     let expected_comment_like = CommentLike {
358       id: inserted_comment_like.id,
359       comment_id: inserted_comment.id,
360       post_id: inserted_post.id,
361       person_id: inserted_person.id,
362       published: inserted_comment_like.published,
363       score: 1,
364     };
365
366     // Comment Saved
367     let comment_saved_form = CommentSavedForm {
368       comment_id: inserted_comment.id,
369       person_id: inserted_person.id,
370     };
371
372     let inserted_comment_saved = CommentSaved::save(pool, &comment_saved_form).await.unwrap();
373
374     let expected_comment_saved = CommentSaved {
375       id: inserted_comment_saved.id,
376       comment_id: inserted_comment.id,
377       person_id: inserted_person.id,
378       published: inserted_comment_saved.published,
379     };
380
381     let comment_update_form = CommentUpdateForm::builder()
382       .content(Some("A test comment".into()))
383       .build();
384
385     let updated_comment = Comment::update(pool, inserted_comment.id, &comment_update_form)
386       .await
387       .unwrap();
388
389     let read_comment = Comment::read(pool, inserted_comment.id).await.unwrap();
390     let like_removed = CommentLike::remove(pool, inserted_person.id, inserted_comment.id)
391       .await
392       .unwrap();
393     let saved_removed = CommentSaved::unsave(pool, &comment_saved_form)
394       .await
395       .unwrap();
396     let num_deleted = Comment::delete(pool, inserted_comment.id).await.unwrap();
397     Comment::delete(pool, inserted_child_comment.id)
398       .await
399       .unwrap();
400     Post::delete(pool, inserted_post.id).await.unwrap();
401     Community::delete(pool, inserted_community.id)
402       .await
403       .unwrap();
404     Person::delete(pool, inserted_person.id).await.unwrap();
405     Instance::delete(pool, inserted_instance.id).await.unwrap();
406
407     assert_eq!(expected_comment, read_comment);
408     assert_eq!(expected_comment, inserted_comment);
409     assert_eq!(expected_comment, updated_comment);
410     assert_eq!(expected_comment_like, inserted_comment_like);
411     assert_eq!(expected_comment_saved, inserted_comment_saved);
412     assert_eq!(
413       format!("0.{}.{}", expected_comment.id, inserted_child_comment.id),
414       inserted_child_comment.path.0,
415     );
416     assert_eq!(1, like_removed);
417     assert_eq!(1, saved_removed);
418     assert_eq!(1, num_deleted);
419   }
420 }