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