1 use diesel::{pg::Pg, result::Error, *};
2 use lemmy_db_queries::{
3 aggregates::post_aggregates::PostAggregates,
13 use lemmy_db_schema::{
26 community::{Community, CommunityFollower, CommunitySafe, CommunityUserBan},
27 post::{Post, PostRead, PostSaved},
28 user::{UserSafe, User_},
34 #[derive(Debug, PartialEq, Serialize, Clone)]
37 pub creator: UserSafe,
38 pub community: CommunitySafe,
39 pub creator_banned_from_community: bool, // Left Join to CommunityUserBan
40 pub counts: PostAggregates,
41 pub subscribed: bool, // Left join to CommunityFollower
42 pub saved: bool, // Left join to PostSaved
43 pub read: bool, // Left join to PostRead
44 pub my_vote: Option<i16>, // Left join to PostLike
47 type PostViewTuple = (
51 Option<CommunityUserBan>,
53 Option<CommunityFollower>,
60 pub fn read(conn: &PgConnection, post_id: i32, my_user_id: Option<i32>) -> Result<Self, Error> {
61 // The left join below will return None in this case
62 let user_id_join = my_user_id.unwrap_or(-1);
68 creator_banned_from_community,
76 .inner_join(user_::table)
77 .inner_join(community::table)
79 community_user_ban::table.on(
81 .eq(community_user_ban::community_id)
82 .and(community_user_ban::user_id.eq(post::creator_id)),
85 .inner_join(post_aggregates::table)
87 community_follower::table.on(
89 .eq(community_follower::community_id)
90 .and(community_follower::user_id.eq(user_id_join)),
96 .eq(post_saved::post_id)
97 .and(post_saved::user_id.eq(user_id_join)),
103 .eq(post_read::post_id)
104 .and(post_read::user_id.eq(user_id_join)),
110 .eq(post_like::post_id)
111 .and(post_like::user_id.eq(user_id_join)),
116 User_::safe_columns_tuple(),
117 Community::safe_columns_tuple(),
118 community_user_ban::all_columns.nullable(),
119 post_aggregates::all_columns,
120 community_follower::all_columns.nullable(),
121 post_saved::all_columns.nullable(),
122 post_read::all_columns.nullable(),
123 post_like::score.nullable(),
125 .first::<PostViewTuple>(conn)?;
131 creator_banned_from_community: creator_banned_from_community.is_some(),
133 subscribed: follower.is_some(),
134 saved: saved.is_some(),
135 read: read.is_some(),
141 pub struct PostQueryBuilder<'a> {
142 conn: &'a PgConnection,
143 listing_type: &'a ListingType,
145 creator_id: Option<i32>,
146 community_id: Option<i32>,
147 community_name: Option<String>,
148 my_user_id: Option<i32>,
149 search_term: Option<String>,
150 url_search: Option<String>,
158 impl<'a> PostQueryBuilder<'a> {
159 pub fn create(conn: &'a PgConnection) -> Self {
162 listing_type: &ListingType::All,
163 sort: &SortType::Hot,
166 community_name: None,
178 pub fn listing_type(mut self, listing_type: &'a ListingType) -> Self {
179 self.listing_type = listing_type;
183 pub fn sort(mut self, sort: &'a SortType) -> Self {
188 pub fn community_id<T: MaybeOptional<i32>>(mut self, community_id: T) -> Self {
189 self.community_id = community_id.get_optional();
193 pub fn my_user_id<T: MaybeOptional<i32>>(mut self, my_user_id: T) -> Self {
194 self.my_user_id = my_user_id.get_optional();
198 pub fn community_name<T: MaybeOptional<String>>(mut self, community_name: T) -> Self {
199 self.community_name = community_name.get_optional();
203 pub fn creator_id<T: MaybeOptional<i32>>(mut self, creator_id: T) -> Self {
204 self.creator_id = creator_id.get_optional();
208 pub fn search_term<T: MaybeOptional<String>>(mut self, search_term: T) -> Self {
209 self.search_term = search_term.get_optional();
213 pub fn url_search<T: MaybeOptional<String>>(mut self, url_search: T) -> Self {
214 self.url_search = url_search.get_optional();
218 pub fn show_nsfw(mut self, show_nsfw: bool) -> Self {
219 self.show_nsfw = show_nsfw;
223 pub fn saved_only(mut self, saved_only: bool) -> Self {
224 self.saved_only = saved_only;
228 pub fn page<T: MaybeOptional<i64>>(mut self, page: T) -> Self {
229 self.page = page.get_optional();
233 pub fn limit<T: MaybeOptional<i64>>(mut self, limit: T) -> Self {
234 self.limit = limit.get_optional();
238 pub fn list(self) -> Result<Vec<PostView>, Error> {
241 // The left join below will return None in this case
242 let user_id_join = self.my_user_id.unwrap_or(-1);
244 let mut query = post::table
245 .inner_join(user_::table)
246 .inner_join(community::table)
248 community_user_ban::table.on(
250 .eq(community_user_ban::community_id)
251 .and(community_user_ban::user_id.eq(community::creator_id)),
254 .inner_join(post_aggregates::table)
256 community_follower::table.on(
258 .eq(community_follower::community_id)
259 .and(community_follower::user_id.eq(user_id_join)),
263 post_saved::table.on(
265 .eq(post_saved::post_id)
266 .and(post_saved::user_id.eq(user_id_join)),
272 .eq(post_read::post_id)
273 .and(post_read::user_id.eq(user_id_join)),
279 .eq(post_like::post_id)
280 .and(post_like::user_id.eq(user_id_join)),
285 User_::safe_columns_tuple(),
286 Community::safe_columns_tuple(),
287 community_user_ban::all_columns.nullable(),
288 post_aggregates::all_columns,
289 community_follower::all_columns.nullable(),
290 post_saved::all_columns.nullable(),
291 post_read::all_columns.nullable(),
292 post_like::score.nullable(),
296 query = match self.listing_type {
297 ListingType::Subscribed => query.filter(community_follower::user_id.is_not_null()), // TODO could be this: and(community_follower::user_id.eq(user_id_join)),
298 ListingType::Local => query.filter(community::local.eq(true)),
302 if let Some(community_id) = self.community_id {
304 .filter(post::community_id.eq(community_id))
305 .then_order_by(post_aggregates::stickied.desc());
308 if let Some(community_name) = self.community_name {
310 .filter(community::name.eq(community_name))
311 .filter(community::local.eq(true))
312 .then_order_by(post_aggregates::stickied.desc());
315 if let Some(url_search) = self.url_search {
316 query = query.filter(post::url.eq(url_search));
319 if let Some(search_term) = self.search_term {
320 let searcher = fuzzy_search(&search_term);
321 query = query.filter(
323 .ilike(searcher.to_owned())
324 .or(post::body.ilike(searcher)),
328 // If its for a specific user, show the removed / deleted
329 if let Some(creator_id) = self.creator_id {
330 query = query.filter(post::creator_id.eq(creator_id));
335 .filter(post::nsfw.eq(false))
336 .filter(community::nsfw.eq(false));
339 // TODO These two might be wrong
341 query = query.filter(post_saved::id.is_not_null());
344 if self.unread_only {
345 query = query.filter(post_read::id.is_not_null());
348 query = match self.sort {
349 SortType::Active => query
351 hot_rank(post_aggregates::score, post_aggregates::newest_comment_time).desc(),
353 .then_order_by(post_aggregates::newest_comment_time.desc()),
354 SortType::Hot => query
355 .then_order_by(hot_rank(post_aggregates::score, post_aggregates::published).desc())
356 .then_order_by(post_aggregates::published.desc()),
357 SortType::New => query.then_order_by(post_aggregates::published.desc()),
358 SortType::TopAll => query.then_order_by(post_aggregates::score.desc()),
359 SortType::TopYear => query
360 .filter(post::published.gt(now - 1.years()))
361 .then_order_by(post_aggregates::score.desc()),
362 SortType::TopMonth => query
363 .filter(post::published.gt(now - 1.months()))
364 .then_order_by(post_aggregates::score.desc()),
365 SortType::TopWeek => query
366 .filter(post::published.gt(now - 1.weeks()))
367 .then_order_by(post_aggregates::score.desc()),
368 SortType::TopDay => query
369 .filter(post::published.gt(now - 1.days()))
370 .then_order_by(post_aggregates::score.desc()),
373 let (limit, offset) = limit_and_offset(self.page, self.limit);
378 .filter(post::removed.eq(false))
379 .filter(post::deleted.eq(false))
380 .filter(community::removed.eq(false))
381 .filter(community::deleted.eq(false));
383 debug!("Post View Query: {:?}", debug_query::<Pg, _>(&query));
385 let res = query.load::<PostViewTuple>(self.conn)?;
387 Ok(PostView::from_tuple_to_vec(res))
391 impl ViewToVec for PostView {
392 type DbTuple = PostViewTuple;
393 fn from_tuple_to_vec(items: Vec<Self::DbTuple>) -> Vec<Self> {
397 post: a.0.to_owned(),
398 creator: a.1.to_owned(),
399 community: a.2.to_owned(),
400 creator_banned_from_community: a.3.is_some(),
401 counts: a.4.to_owned(),
402 subscribed: a.5.is_some(),
403 saved: a.6.is_some(),
407 .collect::<Vec<Self>>()
413 use crate::post_view::{PostQueryBuilder, PostView};
414 use lemmy_db_queries::{
415 aggregates::post_aggregates::PostAggregates,
416 establish_unpooled_connection,
422 use lemmy_db_schema::source::{community::*, post::*, user::*};
426 let conn = establish_unpooled_connection();
428 let user_name = "tegan".to_string();
429 let community_name = "test_community_3".to_string();
430 let post_name = "test post 3".to_string();
432 let new_user = UserForm {
433 name: user_name.to_owned(),
434 preferred_username: None,
435 password_encrypted: "nope".into(),
437 matrix_user_id: None,
445 theme: "browser".into(),
446 default_sort_type: SortType::Hot as i16,
447 default_listing_type: ListingType::Subscribed as i16,
448 lang: "browser".into(),
450 send_notifications_to_email: false,
456 last_refreshed_at: None,
459 let inserted_user = User_::create(&conn, &new_user).unwrap();
461 let new_community = CommunityForm {
462 name: community_name.to_owned(),
463 title: "nada".to_owned(),
465 creator_id: inserted_user.id,
475 last_refreshed_at: None,
481 let inserted_community = Community::create(&conn, &new_community).unwrap();
483 let new_post = PostForm {
484 name: post_name.to_owned(),
487 creator_id: inserted_user.id,
488 community_id: inserted_community.id,
496 embed_description: None,
504 let inserted_post = Post::create(&conn, &new_post).unwrap();
506 let post_like_form = PostLikeForm {
507 post_id: inserted_post.id,
508 user_id: inserted_user.id,
512 let inserted_post_like = PostLike::like(&conn, &post_like_form).unwrap();
514 let expected_post_like = PostLike {
515 id: inserted_post_like.id,
516 post_id: inserted_post.id,
517 user_id: inserted_user.id,
518 published: inserted_post_like.published,
522 let read_post_listings_with_user = PostQueryBuilder::create(&conn)
523 .listing_type(&ListingType::Community)
524 .sort(&SortType::New)
525 .community_id(inserted_community.id)
526 .my_user_id(inserted_user.id)
530 let read_post_listings_no_user = PostQueryBuilder::create(&conn)
531 .listing_type(&ListingType::Community)
532 .sort(&SortType::New)
533 .community_id(inserted_community.id)
537 let read_post_listing_no_user = PostView::read(&conn, inserted_post.id, None).unwrap();
538 let read_post_listing_with_user =
539 PostView::read(&conn, inserted_post.id, Some(inserted_user.id)).unwrap();
541 let agg = PostAggregates::read(&conn, inserted_post.id).unwrap();
543 // the non user version
544 let expected_post_listing_no_user = PostView {
546 id: inserted_post.id,
548 creator_id: inserted_user.id,
551 published: inserted_post.published,
553 community_id: inserted_community.id,
560 embed_description: None,
563 ap_id: inserted_post.ap_id.to_owned(),
568 id: inserted_user.id,
570 preferred_username: None,
571 published: inserted_user.published,
573 actor_id: inserted_user.actor_id.to_owned(),
581 matrix_user_id: None,
583 creator_banned_from_community: false,
584 community: CommunitySafe {
585 id: inserted_community.id,
586 name: community_name,
591 actor_id: inserted_community.actor_id.to_owned(),
593 title: "nada".to_owned(),
595 creator_id: inserted_user.id,
599 published: inserted_community.published,
601 counts: PostAggregates {
603 post_id: inserted_post.id,
609 published: agg.published,
610 newest_comment_time: inserted_post.published,
617 // TODO More needs to be added here
618 let mut expected_post_listing_with_user = expected_post_listing_no_user.to_owned();
619 expected_post_listing_with_user.my_vote = Some(1);
621 let like_removed = PostLike::remove(&conn, inserted_user.id, inserted_post.id).unwrap();
622 let num_deleted = Post::delete(&conn, inserted_post.id).unwrap();
623 Community::delete(&conn, inserted_community.id).unwrap();
624 User_::delete(&conn, inserted_user.id).unwrap();
628 expected_post_listing_with_user,
629 read_post_listings_with_user[0]
631 assert_eq!(expected_post_listing_with_user, read_post_listing_with_user);
632 assert_eq!(1, read_post_listings_with_user.len());
635 assert_eq!(expected_post_listing_no_user, read_post_listings_no_user[0]);
636 assert_eq!(expected_post_listing_no_user, read_post_listing_no_user);
637 assert_eq!(1, read_post_listings_no_user.len());
639 // assert_eq!(expected_post, inserted_post);
640 // assert_eq!(expected_post, updated_post);
641 assert_eq!(expected_post_like, inserted_post_like);
642 assert_eq!(1, like_removed);
643 assert_eq!(1, num_deleted);