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