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