]> Untitled Git - lemmy.git/blob - crates/db_views/src/post_view.rs
Add diesel_async, get rid of blocking function (#2510)
[lemmy.git] / crates / db_views / src / post_view.rs
1 use crate::structs::PostView;
2 use diesel::{
3   debug_query,
4   dsl::*,
5   pg::Pg,
6   result::Error,
7   sql_function,
8   sql_types,
9   BoolExpressionMethods,
10   ExpressionMethods,
11   JoinOnDsl,
12   NullableExpressionMethods,
13   PgTextExpressionMethods,
14   QueryDsl,
15 };
16 use diesel_async::RunQueryDsl;
17 use lemmy_db_schema::{
18   aggregates::structs::PostAggregates,
19   newtypes::{CommunityId, DbUrl, LocalUserId, PersonId, PostId},
20   schema::{
21     community,
22     community_block,
23     community_follower,
24     community_person_ban,
25     local_user_language,
26     person,
27     person_block,
28     person_post_aggregates,
29     post,
30     post_aggregates,
31     post_like,
32     post_read,
33     post_saved,
34   },
35   source::{
36     community::{Community, CommunityFollower, CommunityPersonBan, CommunitySafe},
37     local_user::LocalUser,
38     person::{Person, PersonSafe},
39     person_block::PersonBlock,
40     post::{Post, PostRead, PostSaved},
41   },
42   traits::{ToSafe, ViewToVec},
43   utils::{functions::hot_rank, fuzzy_search, get_conn, limit_and_offset, DbPool},
44   ListingType,
45   SortType,
46 };
47 use tracing::debug;
48 use typed_builder::TypedBuilder;
49
50 type PostViewTuple = (
51   Post,
52   PersonSafe,
53   CommunitySafe,
54   Option<CommunityPersonBan>,
55   PostAggregates,
56   Option<CommunityFollower>,
57   Option<PostSaved>,
58   Option<PostRead>,
59   Option<PersonBlock>,
60   Option<i16>,
61   i64,
62 );
63
64 sql_function!(fn coalesce(x: sql_types::Nullable<sql_types::BigInt>, y: sql_types::BigInt) -> sql_types::BigInt);
65
66 impl PostView {
67   pub async fn read(
68     pool: &DbPool,
69     post_id: PostId,
70     my_person_id: Option<PersonId>,
71   ) -> Result<Self, Error> {
72     let conn = &mut get_conn(pool).await?;
73
74     // The left join below will return None in this case
75     let person_id_join = my_person_id.unwrap_or(PersonId(-1));
76     let (
77       post,
78       creator,
79       community,
80       creator_banned_from_community,
81       counts,
82       follower,
83       saved,
84       read,
85       creator_blocked,
86       post_like,
87       unread_comments,
88     ) = post::table
89       .find(post_id)
90       .inner_join(person::table)
91       .inner_join(community::table)
92       .left_join(
93         community_person_ban::table.on(
94           post::community_id
95             .eq(community_person_ban::community_id)
96             .and(community_person_ban::person_id.eq(post::creator_id))
97             .and(
98               community_person_ban::expires
99                 .is_null()
100                 .or(community_person_ban::expires.gt(now)),
101             ),
102         ),
103       )
104       .inner_join(post_aggregates::table)
105       .left_join(
106         community_follower::table.on(
107           post::community_id
108             .eq(community_follower::community_id)
109             .and(community_follower::person_id.eq(person_id_join)),
110         ),
111       )
112       .left_join(
113         post_saved::table.on(
114           post::id
115             .eq(post_saved::post_id)
116             .and(post_saved::person_id.eq(person_id_join)),
117         ),
118       )
119       .left_join(
120         post_read::table.on(
121           post::id
122             .eq(post_read::post_id)
123             .and(post_read::person_id.eq(person_id_join)),
124         ),
125       )
126       .left_join(
127         person_block::table.on(
128           post::creator_id
129             .eq(person_block::target_id)
130             .and(person_block::person_id.eq(person_id_join)),
131         ),
132       )
133       .left_join(
134         post_like::table.on(
135           post::id
136             .eq(post_like::post_id)
137             .and(post_like::person_id.eq(person_id_join)),
138         ),
139       )
140       .left_join(
141         person_post_aggregates::table.on(
142           post::id
143             .eq(person_post_aggregates::post_id)
144             .and(person_post_aggregates::person_id.eq(person_id_join)),
145         ),
146       )
147       .select((
148         post::all_columns,
149         Person::safe_columns_tuple(),
150         Community::safe_columns_tuple(),
151         community_person_ban::all_columns.nullable(),
152         post_aggregates::all_columns,
153         community_follower::all_columns.nullable(),
154         post_saved::all_columns.nullable(),
155         post_read::all_columns.nullable(),
156         person_block::all_columns.nullable(),
157         post_like::score.nullable(),
158         coalesce(
159           post_aggregates::comments.nullable() - person_post_aggregates::read_comments.nullable(),
160           post_aggregates::comments,
161         ),
162       ))
163       .first::<PostViewTuple>(conn)
164       .await?;
165
166     // If a person is given, then my_vote, if None, should be 0, not null
167     // Necessary to differentiate between other person's votes
168     let my_vote = if my_person_id.is_some() && post_like.is_none() {
169       Some(0)
170     } else {
171       post_like
172     };
173
174     Ok(PostView {
175       post,
176       creator,
177       community,
178       creator_banned_from_community: creator_banned_from_community.is_some(),
179       counts,
180       subscribed: CommunityFollower::to_subscribed_type(&follower),
181       saved: saved.is_some(),
182       read: read.is_some(),
183       creator_blocked: creator_blocked.is_some(),
184       my_vote,
185       unread_comments,
186     })
187   }
188 }
189
190 #[derive(TypedBuilder)]
191 #[builder(field_defaults(default))]
192 pub struct PostQuery<'a> {
193   #[builder(!default)]
194   pool: &'a DbPool,
195   listing_type: Option<ListingType>,
196   sort: Option<SortType>,
197   creator_id: Option<PersonId>,
198   community_id: Option<CommunityId>,
199   community_actor_id: Option<DbUrl>,
200   local_user: Option<&'a LocalUser>,
201   search_term: Option<String>,
202   url_search: Option<String>,
203   saved_only: Option<bool>,
204   page: Option<i64>,
205   limit: Option<i64>,
206 }
207
208 impl<'a> PostQuery<'a> {
209   pub async fn list(self) -> Result<Vec<PostView>, Error> {
210     use diesel::dsl::*;
211     let conn = &mut get_conn(self.pool).await?;
212
213     // The left join below will return None in this case
214     let person_id_join = self.local_user.map(|l| l.person_id).unwrap_or(PersonId(-1));
215     let local_user_id_join = self.local_user.map(|l| l.id).unwrap_or(LocalUserId(-1));
216
217     let mut query = post::table
218       .inner_join(person::table)
219       .inner_join(community::table)
220       .left_join(
221         community_person_ban::table.on(
222           post::community_id
223             .eq(community_person_ban::community_id)
224             .and(community_person_ban::person_id.eq(post::creator_id))
225             .and(
226               community_person_ban::expires
227                 .is_null()
228                 .or(community_person_ban::expires.gt(now)),
229             ),
230         ),
231       )
232       .inner_join(post_aggregates::table)
233       .left_join(
234         community_follower::table.on(
235           post::community_id
236             .eq(community_follower::community_id)
237             .and(community_follower::person_id.eq(person_id_join)),
238         ),
239       )
240       .left_join(
241         post_saved::table.on(
242           post::id
243             .eq(post_saved::post_id)
244             .and(post_saved::person_id.eq(person_id_join)),
245         ),
246       )
247       .left_join(
248         post_read::table.on(
249           post::id
250             .eq(post_read::post_id)
251             .and(post_read::person_id.eq(person_id_join)),
252         ),
253       )
254       .left_join(
255         person_block::table.on(
256           post::creator_id
257             .eq(person_block::target_id)
258             .and(person_block::person_id.eq(person_id_join)),
259         ),
260       )
261       .left_join(
262         community_block::table.on(
263           community::id
264             .eq(community_block::community_id)
265             .and(community_block::person_id.eq(person_id_join)),
266         ),
267       )
268       .left_join(
269         post_like::table.on(
270           post::id
271             .eq(post_like::post_id)
272             .and(post_like::person_id.eq(person_id_join)),
273         ),
274       )
275       .left_join(
276         person_post_aggregates::table.on(
277           post::id
278             .eq(person_post_aggregates::post_id)
279             .and(person_post_aggregates::person_id.eq(person_id_join)),
280         ),
281       )
282       .left_join(
283         local_user_language::table.on(
284           post::language_id
285             .eq(local_user_language::language_id)
286             .and(local_user_language::local_user_id.eq(local_user_id_join)),
287         ),
288       )
289       .select((
290         post::all_columns,
291         Person::safe_columns_tuple(),
292         Community::safe_columns_tuple(),
293         community_person_ban::all_columns.nullable(),
294         post_aggregates::all_columns,
295         community_follower::all_columns.nullable(),
296         post_saved::all_columns.nullable(),
297         post_read::all_columns.nullable(),
298         person_block::all_columns.nullable(),
299         post_like::score.nullable(),
300         coalesce(
301           post_aggregates::comments.nullable() - person_post_aggregates::read_comments.nullable(),
302           post_aggregates::comments,
303         ),
304       ))
305       .into_boxed();
306
307     if let Some(listing_type) = self.listing_type {
308       match listing_type {
309         ListingType::Subscribed => {
310           query = query.filter(community_follower::person_id.is_not_null())
311         }
312         ListingType::Local => {
313           query = query.filter(community::local.eq(true)).filter(
314             community::hidden
315               .eq(false)
316               .or(community_follower::person_id.eq(person_id_join)),
317           );
318         }
319         ListingType::All => {
320           query = query.filter(
321             community::hidden
322               .eq(false)
323               .or(community_follower::person_id.eq(person_id_join)),
324           )
325         }
326       }
327     }
328
329     if let Some(community_id) = self.community_id {
330       query = query
331         .filter(post::community_id.eq(community_id))
332         .then_order_by(post_aggregates::stickied.desc());
333     }
334
335     if let Some(community_actor_id) = self.community_actor_id {
336       query = query
337         .filter(community::actor_id.eq(community_actor_id))
338         .then_order_by(post_aggregates::stickied.desc());
339     }
340
341     if let Some(url_search) = self.url_search {
342       query = query.filter(post::url.eq(url_search));
343     }
344
345     if let Some(search_term) = self.search_term {
346       let searcher = fuzzy_search(&search_term);
347       query = query.filter(
348         post::name
349           .ilike(searcher.to_owned())
350           .or(post::body.ilike(searcher)),
351       );
352     }
353
354     // If its for a specific person, show the removed / deleted
355     if let Some(creator_id) = self.creator_id {
356       query = query.filter(post::creator_id.eq(creator_id));
357     }
358
359     if !self.local_user.map(|l| l.show_nsfw).unwrap_or(false) {
360       query = query
361         .filter(post::nsfw.eq(false))
362         .filter(community::nsfw.eq(false));
363     };
364
365     if !self.local_user.map(|l| l.show_bot_accounts).unwrap_or(true) {
366       query = query.filter(person::bot_account.eq(false));
367     };
368
369     if self.saved_only.unwrap_or(false) {
370       query = query.filter(post_saved::id.is_not_null());
371     }
372     // Only hide the read posts, if the saved_only is false. Otherwise ppl with the hide_read
373     // setting wont be able to see saved posts.
374     else if !self.local_user.map(|l| l.show_read_posts).unwrap_or(true) {
375       query = query.filter(post_read::id.is_null());
376     }
377
378     if self.local_user.is_some() {
379       // Filter out the rows with missing languages
380       query = query.filter(local_user_language::id.is_not_null());
381
382       // Don't show blocked communities or persons
383       query = query.filter(community_block::person_id.is_null());
384       query = query.filter(person_block::person_id.is_null());
385     }
386
387     query = match self.sort.unwrap_or(SortType::Hot) {
388       SortType::Active => query
389         .then_order_by(
390           hot_rank(
391             post_aggregates::score,
392             post_aggregates::newest_comment_time_necro,
393           )
394           .desc(),
395         )
396         .then_order_by(post_aggregates::newest_comment_time_necro.desc()),
397       SortType::Hot => query
398         .then_order_by(hot_rank(post_aggregates::score, post_aggregates::published).desc())
399         .then_order_by(post_aggregates::published.desc()),
400       SortType::New => query.then_order_by(post_aggregates::published.desc()),
401       SortType::Old => query.then_order_by(post_aggregates::published.asc()),
402       SortType::NewComments => query.then_order_by(post_aggregates::newest_comment_time.desc()),
403       SortType::MostComments => query
404         .then_order_by(post_aggregates::comments.desc())
405         .then_order_by(post_aggregates::published.desc()),
406       SortType::TopAll => query
407         .then_order_by(post_aggregates::score.desc())
408         .then_order_by(post_aggregates::published.desc()),
409       SortType::TopYear => query
410         .filter(post_aggregates::published.gt(now - 1.years()))
411         .then_order_by(post_aggregates::score.desc())
412         .then_order_by(post_aggregates::published.desc()),
413       SortType::TopMonth => query
414         .filter(post_aggregates::published.gt(now - 1.months()))
415         .then_order_by(post_aggregates::score.desc())
416         .then_order_by(post_aggregates::published.desc()),
417       SortType::TopWeek => query
418         .filter(post_aggregates::published.gt(now - 1.weeks()))
419         .then_order_by(post_aggregates::score.desc())
420         .then_order_by(post_aggregates::published.desc()),
421       SortType::TopDay => query
422         .filter(post_aggregates::published.gt(now - 1.days()))
423         .then_order_by(post_aggregates::score.desc())
424         .then_order_by(post_aggregates::published.desc()),
425     };
426
427     let (limit, offset) = limit_and_offset(self.page, self.limit)?;
428
429     query = query
430       .limit(limit)
431       .offset(offset)
432       .filter(post::removed.eq(false))
433       .filter(post::deleted.eq(false))
434       .filter(community::removed.eq(false))
435       .filter(community::deleted.eq(false));
436
437     debug!("Post View Query: {:?}", debug_query::<Pg, _>(&query));
438
439     let res = query.load::<PostViewTuple>(conn).await?;
440
441     Ok(PostView::from_tuple_to_vec(res))
442   }
443 }
444
445 impl ViewToVec for PostView {
446   type DbTuple = PostViewTuple;
447   fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
448     items
449       .into_iter()
450       .map(|a| Self {
451         post: a.0,
452         creator: a.1,
453         community: a.2,
454         creator_banned_from_community: a.3.is_some(),
455         counts: a.4,
456         subscribed: CommunityFollower::to_subscribed_type(&a.5),
457         saved: a.6.is_some(),
458         read: a.7.is_some(),
459         creator_blocked: a.8.is_some(),
460         my_vote: a.9,
461         unread_comments: a.10,
462       })
463       .collect::<Vec<Self>>()
464   }
465 }
466
467 #[cfg(test)]
468 mod tests {
469   use crate::post_view::{PostQuery, PostView};
470   use lemmy_db_schema::{
471     aggregates::structs::PostAggregates,
472     newtypes::LanguageId,
473     source::{
474       actor_language::LocalUserLanguage,
475       community::*,
476       community_block::{CommunityBlock, CommunityBlockForm},
477       instance::Instance,
478       language::Language,
479       local_user::{LocalUser, LocalUserInsertForm, LocalUserUpdateForm},
480       person::*,
481       person_block::{PersonBlock, PersonBlockForm},
482       post::*,
483     },
484     traits::{Blockable, Crud, Likeable},
485     utils::{build_db_pool_for_tests, DbPool},
486     SortType,
487     SubscribedType,
488   };
489   use serial_test::serial;
490
491   struct Data {
492     inserted_instance: Instance,
493     inserted_person: Person,
494     inserted_local_user: LocalUser,
495     inserted_blocked_person: Person,
496     inserted_bot: Person,
497     inserted_community: Community,
498     inserted_post: Post,
499   }
500
501   async fn init_data(pool: &DbPool) -> Data {
502     let inserted_instance = Instance::create(pool, "my_domain.tld").await.unwrap();
503
504     let person_name = "tegan".to_string();
505
506     let new_person = PersonInsertForm::builder()
507       .name(person_name.to_owned())
508       .public_key("pubkey".to_string())
509       .instance_id(inserted_instance.id)
510       .build();
511
512     let inserted_person = Person::create(pool, &new_person).await.unwrap();
513
514     let local_user_form = LocalUserInsertForm::builder()
515       .person_id(inserted_person.id)
516       .password_encrypted("".to_string())
517       .build();
518     let inserted_local_user = LocalUser::create(pool, &local_user_form).await.unwrap();
519
520     let new_bot = PersonInsertForm::builder()
521       .name("mybot".to_string())
522       .bot_account(Some(true))
523       .public_key("pubkey".to_string())
524       .instance_id(inserted_instance.id)
525       .build();
526
527     let inserted_bot = Person::create(pool, &new_bot).await.unwrap();
528
529     let new_community = CommunityInsertForm::builder()
530       .name("test_community_3".to_string())
531       .title("nada".to_owned())
532       .public_key("pubkey".to_string())
533       .instance_id(inserted_instance.id)
534       .build();
535
536     let inserted_community = Community::create(pool, &new_community).await.unwrap();
537
538     // Test a person block, make sure the post query doesn't include their post
539     let blocked_person = PersonInsertForm::builder()
540       .name(person_name)
541       .public_key("pubkey".to_string())
542       .instance_id(inserted_instance.id)
543       .build();
544
545     let inserted_blocked_person = Person::create(pool, &blocked_person).await.unwrap();
546
547     let post_from_blocked_person = PostInsertForm::builder()
548       .name("blocked_person_post".to_string())
549       .creator_id(inserted_blocked_person.id)
550       .community_id(inserted_community.id)
551       .language_id(Some(LanguageId(1)))
552       .build();
553
554     Post::create(pool, &post_from_blocked_person).await.unwrap();
555
556     // block that person
557     let person_block = PersonBlockForm {
558       person_id: inserted_person.id,
559       target_id: inserted_blocked_person.id,
560     };
561
562     PersonBlock::block(pool, &person_block).await.unwrap();
563
564     // A sample post
565     let new_post = PostInsertForm::builder()
566       .name("test post 3".to_string())
567       .creator_id(inserted_person.id)
568       .community_id(inserted_community.id)
569       .language_id(Some(LanguageId(47)))
570       .build();
571
572     let inserted_post = Post::create(pool, &new_post).await.unwrap();
573
574     let new_bot_post = PostInsertForm::builder()
575       .name("test bot post".to_string())
576       .creator_id(inserted_bot.id)
577       .community_id(inserted_community.id)
578       .build();
579
580     let _inserted_bot_post = Post::create(pool, &new_bot_post).await.unwrap();
581
582     Data {
583       inserted_instance,
584       inserted_person,
585       inserted_local_user,
586       inserted_blocked_person,
587       inserted_bot,
588       inserted_community,
589       inserted_post,
590     }
591   }
592
593   #[tokio::test]
594   #[serial]
595   async fn post_listing_with_person() {
596     let pool = &build_db_pool_for_tests().await;
597     let data = init_data(pool).await;
598
599     let local_user_form = LocalUserUpdateForm::builder()
600       .show_bot_accounts(Some(false))
601       .build();
602     let inserted_local_user =
603       LocalUser::update(pool, data.inserted_local_user.id, &local_user_form)
604         .await
605         .unwrap();
606
607     let read_post_listing = PostQuery::builder()
608       .pool(pool)
609       .sort(Some(SortType::New))
610       .community_id(Some(data.inserted_community.id))
611       .local_user(Some(&inserted_local_user))
612       .build()
613       .list()
614       .await
615       .unwrap();
616
617     let post_listing_single_with_person =
618       PostView::read(pool, data.inserted_post.id, Some(data.inserted_person.id))
619         .await
620         .unwrap();
621
622     let mut expected_post_listing_with_user = expected_post_view(&data, pool).await;
623
624     // Should be only one person, IE the bot post, and blocked should be missing
625     assert_eq!(1, read_post_listing.len());
626
627     assert_eq!(expected_post_listing_with_user, read_post_listing[0]);
628     expected_post_listing_with_user.my_vote = Some(0);
629     assert_eq!(
630       expected_post_listing_with_user,
631       post_listing_single_with_person
632     );
633
634     let local_user_form = LocalUserUpdateForm::builder()
635       .show_bot_accounts(Some(true))
636       .build();
637     let inserted_local_user =
638       LocalUser::update(pool, data.inserted_local_user.id, &local_user_form)
639         .await
640         .unwrap();
641
642     let post_listings_with_bots = PostQuery::builder()
643       .pool(pool)
644       .sort(Some(SortType::New))
645       .community_id(Some(data.inserted_community.id))
646       .local_user(Some(&inserted_local_user))
647       .build()
648       .list()
649       .await
650       .unwrap();
651     // should include bot post which has "undetermined" language
652     assert_eq!(2, post_listings_with_bots.len());
653
654     cleanup(data, pool).await;
655   }
656
657   #[tokio::test]
658   #[serial]
659   async fn post_listing_no_person() {
660     let pool = &build_db_pool_for_tests().await;
661     let data = init_data(pool).await;
662
663     let read_post_listing_multiple_no_person = PostQuery::builder()
664       .pool(pool)
665       .sort(Some(SortType::New))
666       .community_id(Some(data.inserted_community.id))
667       .build()
668       .list()
669       .await
670       .unwrap();
671
672     let read_post_listing_single_no_person = PostView::read(pool, data.inserted_post.id, None)
673       .await
674       .unwrap();
675
676     let expected_post_listing_no_person = expected_post_view(&data, pool).await;
677
678     // Should be 2 posts, with the bot post, and the blocked
679     assert_eq!(3, read_post_listing_multiple_no_person.len());
680
681     assert_eq!(
682       expected_post_listing_no_person,
683       read_post_listing_multiple_no_person[1]
684     );
685     assert_eq!(
686       expected_post_listing_no_person,
687       read_post_listing_single_no_person
688     );
689
690     cleanup(data, pool).await;
691   }
692
693   #[tokio::test]
694   #[serial]
695   async fn post_listing_block_community() {
696     let pool = &build_db_pool_for_tests().await;
697     let data = init_data(pool).await;
698
699     let community_block = CommunityBlockForm {
700       person_id: data.inserted_person.id,
701       community_id: data.inserted_community.id,
702     };
703     CommunityBlock::block(pool, &community_block).await.unwrap();
704
705     let read_post_listings_with_person_after_block = PostQuery::builder()
706       .pool(pool)
707       .sort(Some(SortType::New))
708       .community_id(Some(data.inserted_community.id))
709       .local_user(Some(&data.inserted_local_user))
710       .build()
711       .list()
712       .await
713       .unwrap();
714     // Should be 0 posts after the community block
715     assert_eq!(0, read_post_listings_with_person_after_block.len());
716
717     CommunityBlock::unblock(pool, &community_block)
718       .await
719       .unwrap();
720     cleanup(data, pool).await;
721   }
722
723   #[tokio::test]
724   #[serial]
725   async fn post_listing_like() {
726     let pool = &build_db_pool_for_tests().await;
727     let data = init_data(pool).await;
728
729     let post_like_form = PostLikeForm {
730       post_id: data.inserted_post.id,
731       person_id: data.inserted_person.id,
732       score: 1,
733     };
734
735     let inserted_post_like = PostLike::like(pool, &post_like_form).await.unwrap();
736
737     let expected_post_like = PostLike {
738       id: inserted_post_like.id,
739       post_id: data.inserted_post.id,
740       person_id: data.inserted_person.id,
741       published: inserted_post_like.published,
742       score: 1,
743     };
744     assert_eq!(expected_post_like, inserted_post_like);
745
746     let like_removed = PostLike::remove(pool, data.inserted_person.id, data.inserted_post.id)
747       .await
748       .unwrap();
749     assert_eq!(1, like_removed);
750     cleanup(data, pool).await;
751   }
752
753   #[tokio::test]
754   #[serial]
755   async fn post_listing_person_language() {
756     let pool = &build_db_pool_for_tests().await;
757     let data = init_data(pool).await;
758
759     let spanish_id = Language::read_id_from_code(pool, "es").await.unwrap();
760     let post_spanish = PostInsertForm::builder()
761       .name("asffgdsc".to_string())
762       .creator_id(data.inserted_person.id)
763       .community_id(data.inserted_community.id)
764       .language_id(Some(spanish_id))
765       .build();
766
767     Post::create(pool, &post_spanish).await.unwrap();
768
769     let post_listings_all = PostQuery::builder()
770       .pool(pool)
771       .sort(Some(SortType::New))
772       .local_user(Some(&data.inserted_local_user))
773       .build()
774       .list()
775       .await
776       .unwrap();
777
778     // no language filters specified, all posts should be returned
779     assert_eq!(3, post_listings_all.len());
780
781     let french_id = Language::read_id_from_code(pool, "fr").await.unwrap();
782     LocalUserLanguage::update(pool, vec![french_id], data.inserted_local_user.id)
783       .await
784       .unwrap();
785
786     let post_listing_french = PostQuery::builder()
787       .pool(pool)
788       .sort(Some(SortType::New))
789       .local_user(Some(&data.inserted_local_user))
790       .build()
791       .list()
792       .await
793       .unwrap();
794
795     // only one french language post should be returned
796     assert_eq!(1, post_listing_french.len());
797     assert_eq!(french_id, post_listing_french[0].post.language_id);
798
799     let undetermined_id = Language::read_id_from_code(pool, "und").await.unwrap();
800     LocalUserLanguage::update(
801       pool,
802       vec![french_id, undetermined_id],
803       data.inserted_local_user.id,
804     )
805     .await
806     .unwrap();
807     let post_listings_french_und = PostQuery::builder()
808       .pool(pool)
809       .sort(Some(SortType::New))
810       .local_user(Some(&data.inserted_local_user))
811       .build()
812       .list()
813       .await
814       .unwrap();
815
816     // french post and undetermined language post should be returned
817     assert_eq!(2, post_listings_french_und.len());
818     assert_eq!(
819       undetermined_id,
820       post_listings_french_und[0].post.language_id
821     );
822     assert_eq!(french_id, post_listings_french_und[1].post.language_id);
823
824     cleanup(data, pool).await;
825   }
826
827   async fn cleanup(data: Data, pool: &DbPool) {
828     let num_deleted = Post::delete(pool, data.inserted_post.id).await.unwrap();
829     Community::delete(pool, data.inserted_community.id)
830       .await
831       .unwrap();
832     Person::delete(pool, data.inserted_person.id).await.unwrap();
833     Person::delete(pool, data.inserted_bot.id).await.unwrap();
834     Person::delete(pool, data.inserted_blocked_person.id)
835       .await
836       .unwrap();
837     Instance::delete(pool, data.inserted_instance.id)
838       .await
839       .unwrap();
840     assert_eq!(1, num_deleted);
841   }
842
843   async fn expected_post_view(data: &Data, pool: &DbPool) -> PostView {
844     let (inserted_person, inserted_community, inserted_post) = (
845       &data.inserted_person,
846       &data.inserted_community,
847       &data.inserted_post,
848     );
849     let agg = PostAggregates::read(pool, inserted_post.id).await.unwrap();
850
851     PostView {
852       post: Post {
853         id: inserted_post.id,
854         name: inserted_post.name.clone(),
855         creator_id: inserted_person.id,
856         url: None,
857         body: None,
858         published: inserted_post.published,
859         updated: None,
860         community_id: inserted_community.id,
861         removed: false,
862         deleted: false,
863         locked: false,
864         stickied: false,
865         nsfw: false,
866         embed_title: None,
867         embed_description: None,
868         embed_video_url: None,
869         thumbnail_url: None,
870         ap_id: inserted_post.ap_id.to_owned(),
871         local: true,
872         language_id: LanguageId(47),
873       },
874       my_vote: None,
875       unread_comments: 0,
876       creator: PersonSafe {
877         id: inserted_person.id,
878         name: inserted_person.name.clone(),
879         display_name: None,
880         published: inserted_person.published,
881         avatar: None,
882         actor_id: inserted_person.actor_id.to_owned(),
883         local: true,
884         admin: false,
885         bot_account: false,
886         banned: false,
887         deleted: false,
888         bio: None,
889         banner: None,
890         updated: None,
891         inbox_url: inserted_person.inbox_url.to_owned(),
892         shared_inbox_url: None,
893         matrix_user_id: None,
894         ban_expires: None,
895         instance_id: data.inserted_instance.id,
896       },
897       creator_banned_from_community: false,
898       community: CommunitySafe {
899         id: inserted_community.id,
900         name: inserted_community.name.clone(),
901         icon: None,
902         removed: false,
903         deleted: false,
904         nsfw: false,
905         actor_id: inserted_community.actor_id.to_owned(),
906         local: true,
907         title: "nada".to_owned(),
908         description: None,
909         updated: None,
910         banner: None,
911         hidden: false,
912         posting_restricted_to_mods: false,
913         published: inserted_community.published,
914         instance_id: data.inserted_instance.id,
915       },
916       counts: PostAggregates {
917         id: agg.id,
918         post_id: inserted_post.id,
919         comments: 0,
920         score: 0,
921         upvotes: 0,
922         downvotes: 0,
923         stickied: false,
924         published: agg.published,
925         newest_comment_time_necro: inserted_post.published,
926         newest_comment_time: inserted_post.published,
927       },
928       subscribed: SubscribedType::NotSubscribed,
929       read: false,
930       saved: false,
931       creator_blocked: false,
932     }
933   }
934 }