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