]> Untitled Git - lemmy.git/blob - crates/db_schema/src/impls/post.rs
Diesel 2.0.0 upgrade (#2452)
[lemmy.git] / crates / db_schema / src / impls / post.rs
1 use crate::{
2   newtypes::{CommunityId, DbUrl, PersonId, PostId},
3   source::post::{
4     Post,
5     PostForm,
6     PostLike,
7     PostLikeForm,
8     PostRead,
9     PostReadForm,
10     PostSaved,
11     PostSavedForm,
12   },
13   traits::{Crud, DeleteableOrRemoveable, Likeable, Readable, Saveable},
14   utils::{naive_now, FETCH_LIMIT_MAX},
15 };
16 use diesel::{dsl::*, result::Error, ExpressionMethods, PgConnection, QueryDsl, RunQueryDsl, *};
17 use url::Url;
18
19 impl Crud for Post {
20   type Form = PostForm;
21   type IdType = PostId;
22   fn read(conn: &mut PgConnection, post_id: PostId) -> Result<Self, Error> {
23     use crate::schema::post::dsl::*;
24     post.find(post_id).first::<Self>(conn)
25   }
26
27   fn delete(conn: &mut PgConnection, post_id: PostId) -> Result<usize, Error> {
28     use crate::schema::post::dsl::*;
29     diesel::delete(post.find(post_id)).execute(conn)
30   }
31
32   fn create(conn: &mut PgConnection, new_post: &PostForm) -> Result<Self, Error> {
33     use crate::schema::post::dsl::*;
34     insert_into(post).values(new_post).get_result::<Self>(conn)
35   }
36
37   fn update(conn: &mut PgConnection, post_id: PostId, new_post: &PostForm) -> Result<Self, Error> {
38     use crate::schema::post::dsl::*;
39     diesel::update(post.find(post_id))
40       .set(new_post)
41       .get_result::<Self>(conn)
42   }
43 }
44
45 impl Post {
46   pub fn list_for_community(
47     conn: &mut PgConnection,
48     the_community_id: CommunityId,
49   ) -> Result<Vec<Self>, Error> {
50     use crate::schema::post::dsl::*;
51     post
52       .filter(community_id.eq(the_community_id))
53       .filter(deleted.eq(false))
54       .filter(removed.eq(false))
55       .then_order_by(published.desc())
56       .then_order_by(stickied.desc())
57       .limit(FETCH_LIMIT_MAX)
58       .load::<Self>(conn)
59   }
60
61   pub fn update_ap_id(
62     conn: &mut PgConnection,
63     post_id: PostId,
64     apub_id: DbUrl,
65   ) -> Result<Self, Error> {
66     use crate::schema::post::dsl::*;
67
68     diesel::update(post.find(post_id))
69       .set(ap_id.eq(apub_id))
70       .get_result::<Self>(conn)
71   }
72
73   pub fn permadelete_for_creator(
74     conn: &mut PgConnection,
75     for_creator_id: PersonId,
76   ) -> Result<Vec<Self>, Error> {
77     use crate::schema::post::dsl::*;
78
79     let perma_deleted = "*Permananently Deleted*";
80     let perma_deleted_url = "https://deleted.com";
81
82     diesel::update(post.filter(creator_id.eq(for_creator_id)))
83       .set((
84         name.eq(perma_deleted),
85         url.eq(perma_deleted_url),
86         body.eq(perma_deleted),
87         deleted.eq(true),
88         updated.eq(naive_now()),
89       ))
90       .get_results::<Self>(conn)
91   }
92
93   pub fn update_deleted(
94     conn: &mut PgConnection,
95     post_id: PostId,
96     new_deleted: bool,
97   ) -> Result<Self, Error> {
98     use crate::schema::post::dsl::*;
99     diesel::update(post.find(post_id))
100       .set((deleted.eq(new_deleted), updated.eq(naive_now())))
101       .get_result::<Self>(conn)
102   }
103
104   pub fn update_removed(
105     conn: &mut PgConnection,
106     post_id: PostId,
107     new_removed: bool,
108   ) -> Result<Self, Error> {
109     use crate::schema::post::dsl::*;
110     diesel::update(post.find(post_id))
111       .set((removed.eq(new_removed), updated.eq(naive_now())))
112       .get_result::<Self>(conn)
113   }
114
115   pub fn update_removed_for_creator(
116     conn: &mut PgConnection,
117     for_creator_id: PersonId,
118     for_community_id: Option<CommunityId>,
119     new_removed: bool,
120   ) -> Result<Vec<Self>, Error> {
121     use crate::schema::post::dsl::*;
122
123     let mut update = diesel::update(post).into_boxed();
124     update = update.filter(creator_id.eq(for_creator_id));
125
126     if let Some(for_community_id) = for_community_id {
127       update = update.filter(community_id.eq(for_community_id));
128     }
129
130     update
131       .set((removed.eq(new_removed), updated.eq(naive_now())))
132       .get_results::<Self>(conn)
133   }
134
135   pub fn update_locked(
136     conn: &mut PgConnection,
137     post_id: PostId,
138     new_locked: bool,
139   ) -> Result<Self, Error> {
140     use crate::schema::post::dsl::*;
141     diesel::update(post.find(post_id))
142       .set(locked.eq(new_locked))
143       .get_result::<Self>(conn)
144   }
145
146   pub fn update_stickied(
147     conn: &mut PgConnection,
148     post_id: PostId,
149     new_stickied: bool,
150   ) -> Result<Self, Error> {
151     use crate::schema::post::dsl::*;
152     diesel::update(post.find(post_id))
153       .set(stickied.eq(new_stickied))
154       .get_result::<Self>(conn)
155   }
156
157   pub fn is_post_creator(person_id: PersonId, post_creator_id: PersonId) -> bool {
158     person_id == post_creator_id
159   }
160
161   pub fn upsert(conn: &mut PgConnection, post_form: &PostForm) -> Result<Post, Error> {
162     use crate::schema::post::dsl::*;
163     insert_into(post)
164       .values(post_form)
165       .on_conflict(ap_id)
166       .do_update()
167       .set(post_form)
168       .get_result::<Self>(conn)
169   }
170   pub fn read_from_apub_id(conn: &mut PgConnection, object_id: Url) -> Result<Option<Self>, Error> {
171     use crate::schema::post::dsl::*;
172     let object_id: DbUrl = object_id.into();
173     Ok(
174       post
175         .filter(ap_id.eq(object_id))
176         .first::<Post>(conn)
177         .ok()
178         .map(Into::into),
179     )
180   }
181
182   pub fn fetch_pictrs_posts_for_creator(
183     conn: &mut PgConnection,
184     for_creator_id: PersonId,
185   ) -> Result<Vec<Self>, Error> {
186     use crate::schema::post::dsl::*;
187     let pictrs_search = "%pictrs/image%";
188
189     post
190       .filter(creator_id.eq(for_creator_id))
191       .filter(url.like(pictrs_search))
192       .load::<Self>(conn)
193   }
194
195   /// Sets the url and thumbnails fields to None
196   pub fn remove_pictrs_post_images_and_thumbnails_for_creator(
197     conn: &mut PgConnection,
198     for_creator_id: PersonId,
199   ) -> Result<Vec<Self>, Error> {
200     use crate::schema::post::dsl::*;
201     let pictrs_search = "%pictrs/image%";
202
203     diesel::update(
204       post
205         .filter(creator_id.eq(for_creator_id))
206         .filter(url.like(pictrs_search)),
207     )
208     .set((
209       url.eq::<Option<String>>(None),
210       thumbnail_url.eq::<Option<String>>(None),
211     ))
212     .get_results::<Self>(conn)
213   }
214
215   pub fn fetch_pictrs_posts_for_community(
216     conn: &mut PgConnection,
217     for_community_id: CommunityId,
218   ) -> Result<Vec<Self>, Error> {
219     use crate::schema::post::dsl::*;
220     let pictrs_search = "%pictrs/image%";
221     post
222       .filter(community_id.eq(for_community_id))
223       .filter(url.like(pictrs_search))
224       .load::<Self>(conn)
225   }
226
227   /// Sets the url and thumbnails fields to None
228   pub fn remove_pictrs_post_images_and_thumbnails_for_community(
229     conn: &mut PgConnection,
230     for_community_id: CommunityId,
231   ) -> Result<Vec<Self>, Error> {
232     use crate::schema::post::dsl::*;
233     let pictrs_search = "%pictrs/image%";
234
235     diesel::update(
236       post
237         .filter(community_id.eq(for_community_id))
238         .filter(url.like(pictrs_search)),
239     )
240     .set((
241       url.eq::<Option<String>>(None),
242       thumbnail_url.eq::<Option<String>>(None),
243     ))
244     .get_results::<Self>(conn)
245   }
246 }
247
248 impl Likeable for PostLike {
249   type Form = PostLikeForm;
250   type IdType = PostId;
251   fn like(conn: &mut PgConnection, post_like_form: &PostLikeForm) -> Result<Self, Error> {
252     use crate::schema::post_like::dsl::*;
253     insert_into(post_like)
254       .values(post_like_form)
255       .on_conflict((post_id, person_id))
256       .do_update()
257       .set(post_like_form)
258       .get_result::<Self>(conn)
259   }
260   fn remove(conn: &mut PgConnection, person_id: PersonId, post_id: PostId) -> Result<usize, Error> {
261     use crate::schema::post_like::dsl;
262     diesel::delete(
263       dsl::post_like
264         .filter(dsl::post_id.eq(post_id))
265         .filter(dsl::person_id.eq(person_id)),
266     )
267     .execute(conn)
268   }
269 }
270
271 impl Saveable for PostSaved {
272   type Form = PostSavedForm;
273   fn save(conn: &mut PgConnection, post_saved_form: &PostSavedForm) -> Result<Self, Error> {
274     use crate::schema::post_saved::dsl::*;
275     insert_into(post_saved)
276       .values(post_saved_form)
277       .on_conflict((post_id, person_id))
278       .do_update()
279       .set(post_saved_form)
280       .get_result::<Self>(conn)
281   }
282   fn unsave(conn: &mut PgConnection, post_saved_form: &PostSavedForm) -> Result<usize, Error> {
283     use crate::schema::post_saved::dsl::*;
284     diesel::delete(
285       post_saved
286         .filter(post_id.eq(post_saved_form.post_id))
287         .filter(person_id.eq(post_saved_form.person_id)),
288     )
289     .execute(conn)
290   }
291 }
292
293 impl Readable for PostRead {
294   type Form = PostReadForm;
295   fn mark_as_read(conn: &mut PgConnection, post_read_form: &PostReadForm) -> Result<Self, Error> {
296     use crate::schema::post_read::dsl::*;
297     insert_into(post_read)
298       .values(post_read_form)
299       .on_conflict((post_id, person_id))
300       .do_update()
301       .set(post_read_form)
302       .get_result::<Self>(conn)
303   }
304
305   fn mark_as_unread(
306     conn: &mut PgConnection,
307     post_read_form: &PostReadForm,
308   ) -> Result<usize, Error> {
309     use crate::schema::post_read::dsl::*;
310     diesel::delete(
311       post_read
312         .filter(post_id.eq(post_read_form.post_id))
313         .filter(person_id.eq(post_read_form.person_id)),
314     )
315     .execute(conn)
316   }
317 }
318
319 impl DeleteableOrRemoveable for Post {
320   fn blank_out_deleted_or_removed_info(mut self) -> Self {
321     self.name = "".into();
322     self.url = None;
323     self.body = None;
324     self.embed_title = None;
325     self.embed_description = None;
326     self.embed_video_url = None;
327     self.thumbnail_url = None;
328
329     self
330   }
331 }
332
333 #[cfg(test)]
334 mod tests {
335   use crate::{
336     source::{
337       community::{Community, CommunityForm},
338       person::*,
339       post::*,
340     },
341     traits::{Crud, Likeable, Readable, Saveable},
342     utils::establish_unpooled_connection,
343   };
344   use serial_test::serial;
345
346   #[test]
347   #[serial]
348   fn test_crud() {
349     let conn = &mut establish_unpooled_connection();
350
351     let new_person = PersonForm {
352       name: "jim".into(),
353       public_key: Some("pubkey".to_string()),
354       ..PersonForm::default()
355     };
356
357     let inserted_person = Person::create(conn, &new_person).unwrap();
358
359     let new_community = CommunityForm {
360       name: "test community_3".to_string(),
361       title: "nada".to_owned(),
362       public_key: Some("pubkey".to_string()),
363       ..CommunityForm::default()
364     };
365
366     let inserted_community = Community::create(conn, &new_community).unwrap();
367
368     let new_post = PostForm {
369       name: "A test post".into(),
370       creator_id: inserted_person.id,
371       community_id: inserted_community.id,
372       ..PostForm::default()
373     };
374
375     let inserted_post = Post::create(conn, &new_post).unwrap();
376
377     let expected_post = Post {
378       id: inserted_post.id,
379       name: "A test post".into(),
380       url: None,
381       body: None,
382       creator_id: inserted_person.id,
383       community_id: inserted_community.id,
384       published: inserted_post.published,
385       removed: false,
386       locked: false,
387       stickied: false,
388       nsfw: false,
389       deleted: false,
390       updated: None,
391       embed_title: None,
392       embed_description: None,
393       embed_video_url: None,
394       thumbnail_url: None,
395       ap_id: inserted_post.ap_id.to_owned(),
396       local: true,
397       language_id: Default::default(),
398     };
399
400     // Post Like
401     let post_like_form = PostLikeForm {
402       post_id: inserted_post.id,
403       person_id: inserted_person.id,
404       score: 1,
405     };
406
407     let inserted_post_like = PostLike::like(conn, &post_like_form).unwrap();
408
409     let expected_post_like = PostLike {
410       id: inserted_post_like.id,
411       post_id: inserted_post.id,
412       person_id: inserted_person.id,
413       published: inserted_post_like.published,
414       score: 1,
415     };
416
417     // Post Save
418     let post_saved_form = PostSavedForm {
419       post_id: inserted_post.id,
420       person_id: inserted_person.id,
421     };
422
423     let inserted_post_saved = PostSaved::save(conn, &post_saved_form).unwrap();
424
425     let expected_post_saved = PostSaved {
426       id: inserted_post_saved.id,
427       post_id: inserted_post.id,
428       person_id: inserted_person.id,
429       published: inserted_post_saved.published,
430     };
431
432     // Post Read
433     let post_read_form = PostReadForm {
434       post_id: inserted_post.id,
435       person_id: inserted_person.id,
436     };
437
438     let inserted_post_read = PostRead::mark_as_read(conn, &post_read_form).unwrap();
439
440     let expected_post_read = PostRead {
441       id: inserted_post_read.id,
442       post_id: inserted_post.id,
443       person_id: inserted_person.id,
444       published: inserted_post_read.published,
445     };
446
447     let read_post = Post::read(conn, inserted_post.id).unwrap();
448     let updated_post = Post::update(conn, inserted_post.id, &new_post).unwrap();
449     let like_removed = PostLike::remove(conn, inserted_person.id, inserted_post.id).unwrap();
450     let saved_removed = PostSaved::unsave(conn, &post_saved_form).unwrap();
451     let read_removed = PostRead::mark_as_unread(conn, &post_read_form).unwrap();
452     let num_deleted = Post::delete(conn, inserted_post.id).unwrap();
453     Community::delete(conn, inserted_community.id).unwrap();
454     Person::delete(conn, inserted_person.id).unwrap();
455
456     assert_eq!(expected_post, read_post);
457     assert_eq!(expected_post, inserted_post);
458     assert_eq!(expected_post, updated_post);
459     assert_eq!(expected_post_like, inserted_post_like);
460     assert_eq!(expected_post_saved, inserted_post_saved);
461     assert_eq!(expected_post_read, inserted_post_read);
462     assert_eq!(1, like_removed);
463     assert_eq!(1, saved_removed);
464     assert_eq!(1, read_removed);
465     assert_eq!(1, num_deleted);
466   }
467 }