From fb147b778b4ffb47e488e9c3ae698c8286fbd5cb Mon Sep 17 00:00:00 2001 From: dull b Date: Wed, 5 Jul 2023 01:51:17 +0000 Subject: [PATCH] Start over --- crates/api/src/comment/distinguish.rs | 11 +- crates/api/src/comment/like.rs | 16 +- crates/api/src/comment/save.rs | 7 +- crates/api/src/comment_report/create.rs | 13 +- crates/api/src/comment_report/list.rs | 2 +- crates/api/src/comment_report/resolve.rs | 11 +- crates/api/src/community/add_mod.rs | 18 +- crates/api/src/community/ban.rs | 17 +- crates/api/src/community/block.rs | 8 +- crates/api/src/community/follow.rs | 21 +- crates/api/src/community/hide.rs | 4 +- crates/api/src/community/transfer.rs | 17 +- crates/api/src/lib.rs | 20 +- crates/api/src/local_user/add_admin.rs | 6 +- crates/api/src/local_user/ban_person.rs | 6 +- crates/api/src/local_user/block.rs | 6 +- crates/api/src/local_user/change_password.rs | 2 +- .../local_user/change_password_after_reset.rs | 11 +- crates/api/src/local_user/get_captcha.rs | 4 +- crates/api/src/local_user/list_banned.rs | 2 +- crates/api/src/local_user/login.rs | 16 +- .../local_user/notifications/list_mentions.rs | 2 +- .../local_user/notifications/list_replies.rs | 2 +- .../local_user/notifications/mark_all_read.rs | 6 +- .../notifications/mark_mention_read.rs | 6 +- .../notifications/mark_reply_read.rs | 6 +- .../local_user/notifications/unread_count.rs | 6 +- crates/api/src/local_user/report_count.rs | 8 +- crates/api/src/local_user/reset_password.rs | 6 +- crates/api/src/local_user/save_settings.rs | 18 +- crates/api/src/local_user/verify_email.rs | 7 +- crates/api/src/post/feature.rs | 12 +- crates/api/src/post/like.rs | 19 +- crates/api/src/post/lock.rs | 12 +- crates/api/src/post/mark_read.rs | 6 +- crates/api/src/post/save.rs | 8 +- crates/api/src/post_report/create.rs | 13 +- crates/api/src/post_report/list.rs | 2 +- crates/api/src/post_report/resolve.rs | 11 +- crates/api/src/private_message/mark_read.rs | 7 +- .../api/src/private_message_report/create.rs | 10 +- crates/api/src/private_message_report/list.rs | 2 +- .../api/src/private_message_report/resolve.rs | 6 +- crates/api/src/site/federated_instances.rs | 2 +- crates/api/src/site/leave_admin.rs | 19 +- crates/api/src/site/mod_log.rs | 38 +-- crates/api/src/site/purge/comment.rs | 6 +- crates/api/src/site/purge/community.rs | 6 +- crates/api/src/site/purge/person.rs | 6 +- crates/api/src/site/purge/post.rs | 6 +- .../site/registration_applications/approve.rs | 9 +- .../site/registration_applications/list.rs | 4 +- .../registration_applications/unread_count.rs | 5 +- crates/api_common/src/build_response.rs | 38 +-- crates/api_common/src/context.rs | 9 +- crates/api_common/src/utils.rs | 120 +++---- crates/api_crud/src/comment/create.rs | 37 +-- crates/api_crud/src/comment/delete.rs | 8 +- crates/api_crud/src/comment/read.rs | 2 +- crates/api_crud/src/comment/remove.rs | 12 +- crates/api_crud/src/comment/update.rs | 10 +- crates/api_crud/src/community/create.rs | 15 +- crates/api_crud/src/community/delete.rs | 4 +- crates/api_crud/src/community/list.rs | 4 +- crates/api_crud/src/community/remove.rs | 4 +- crates/api_crud/src/community/update.rs | 15 +- crates/api_crud/src/custom_emoji/create.rs | 8 +- crates/api_crud/src/custom_emoji/delete.rs | 2 +- crates/api_crud/src/custom_emoji/update.rs | 10 +- crates/api_crud/src/post/create.rs | 38 +-- crates/api_crud/src/post/delete.rs | 8 +- crates/api_crud/src/post/read.rs | 41 +-- crates/api_crud/src/post/remove.rs | 10 +- crates/api_crud/src/post/update.rs | 10 +- crates/api_crud/src/private_message/create.rs | 17 +- crates/api_crud/src/private_message/delete.rs | 7 +- crates/api_crud/src/private_message/read.rs | 2 +- crates/api_crud/src/private_message/update.rs | 9 +- crates/api_crud/src/site/create.rs | 13 +- crates/api_crud/src/site/read.rs | 25 +- crates/api_crud/src/site/update.rs | 22 +- crates/api_crud/src/user/create.rs | 23 +- .../apub/src/activities/block/block_user.rs | 14 +- crates/apub/src/activities/block/mod.rs | 19 +- .../src/activities/block/undo_block_user.rs | 12 +- .../activities/community/collection_add.rs | 17 +- .../activities/community/collection_remove.rs | 8 +- .../src/activities/community/lock_page.rs | 6 +- crates/apub/src/activities/community/mod.rs | 2 +- .../apub/src/activities/community/report.rs | 4 +- .../apub/src/activities/community/update.rs | 6 +- .../activities/create_or_update/comment.rs | 16 +- .../src/activities/create_or_update/post.rs | 10 +- .../create_or_update/private_message.rs | 6 +- crates/apub/src/activities/deletion/delete.rs | 12 +- .../src/activities/deletion/delete_user.rs | 2 +- crates/apub/src/activities/deletion/mod.rs | 29 +- .../src/activities/deletion/undo_delete.rs | 12 +- .../apub/src/activities/following/accept.rs | 2 +- .../apub/src/activities/following/follow.rs | 8 +- crates/apub/src/activities/following/mod.rs | 2 +- .../src/activities/following/undo_follow.rs | 4 +- crates/apub/src/activities/mod.rs | 4 +- crates/apub/src/activities/voting/mod.rs | 18 +- crates/apub/src/activities/voting/vote.rs | 2 +- crates/apub/src/api/list_comments.rs | 6 +- crates/apub/src/api/list_posts.rs | 14 +- crates/apub/src/api/read_community.rs | 21 +- crates/apub/src/api/read_person.rs | 11 +- crates/apub/src/api/resolve_object.rs | 16 +- crates/apub/src/api/search.rs | 20 +- .../src/collections/community_featured.rs | 2 +- .../src/collections/community_moderators.rs | 44 +-- .../apub/src/collections/community_outbox.rs | 6 +- crates/apub/src/fetcher/mod.rs | 4 +- crates/apub/src/fetcher/post_or_comment.rs | 8 +- crates/apub/src/http/comment.rs | 2 +- crates/apub/src/http/community.rs | 11 +- crates/apub/src/http/mod.rs | 2 +- crates/apub/src/http/person.rs | 4 +- crates/apub/src/http/post.rs | 2 +- crates/apub/src/http/site.rs | 5 +- crates/apub/src/lib.rs | 10 +- crates/apub/src/mentions.rs | 12 +- crates/apub/src/objects/comment.rs | 50 +-- crates/apub/src/objects/community.rs | 23 +- crates/apub/src/objects/instance.rs | 28 +- crates/apub/src/objects/person.rs | 14 +- crates/apub/src/objects/post.rs | 35 +- crates/apub/src/objects/private_message.rs | 30 +- .../activities/community/collection_add.rs | 2 +- .../activities/community/collection_remove.rs | 2 +- .../activities/community/lock_page.rs | 2 +- .../activities/create_or_update/note.rs | 2 +- .../protocol/activities/deletion/delete.rs | 4 +- .../protocol/collections/group_followers.rs | 2 +- crates/apub/src/protocol/objects/mod.rs | 18 +- crates/apub/src/protocol/objects/note.rs | 4 +- .../src/aggregates/comment_aggregates.rs | 73 ++--- .../src/aggregates/community_aggregates.rs | 89 +++-- .../src/aggregates/person_aggregates.rs | 101 +++--- .../src/aggregates/person_post_aggregates.rs | 17 +- .../src/aggregates/post_aggregates.rs | 82 ++--- .../src/aggregates/site_aggregates.rs | 64 ++-- crates/db_schema/src/impls/activity.rs | 48 ++- crates/db_schema/src/impls/actor_language.rs | 253 +++++++-------- crates/db_schema/src/impls/captcha_answer.rs | 31 +- crates/db_schema/src/impls/comment.rs | 124 +++---- crates/db_schema/src/impls/comment_reply.rs | 77 ++--- crates/db_schema/src/impls/comment_report.rs | 16 +- crates/db_schema/src/impls/community.rs | 125 +++---- crates/db_schema/src/impls/community_block.rs | 13 +- crates/db_schema/src/impls/custom_emoji.rs | 19 +- .../db_schema/src/impls/email_verification.rs | 13 +- .../src/impls/federation_allowlist.rs | 25 +- .../src/impls/federation_blocklist.rs | 9 +- crates/db_schema/src/impls/instance.rs | 24 +- crates/db_schema/src/impls/language.rs | 21 +- crates/db_schema/src/impls/local_site.rs | 16 +- .../src/impls/local_site_rate_limit.rs | 19 +- crates/db_schema/src/impls/local_user.rs | 39 ++- crates/db_schema/src/impls/moderator.rs | 306 ++++++++---------- .../src/impls/password_reset_request.rs | 50 ++- crates/db_schema/src/impls/person.rs | 88 ++--- crates/db_schema/src/impls/person_block.rs | 16 +- crates/db_schema/src/impls/person_mention.rs | 66 ++-- crates/db_schema/src/impls/post.rs | 120 +++---- crates/db_schema/src/impls/post_report.rs | 16 +- crates/db_schema/src/impls/private_message.rs | 57 ++-- .../src/impls/private_message_report.rs | 16 +- .../src/impls/registration_application.rs | 24 +- crates/db_schema/src/impls/secret.rs | 15 +- crates/db_schema/src/impls/site.rs | 34 +- crates/db_schema/src/impls/tagline.rs | 17 +- crates/db_schema/src/traits.rs | 59 ++-- crates/db_schema/src/utils.rs | 98 +----- crates/db_views/src/comment_report_view.rs | 80 +++-- crates/db_views/src/comment_view.rs | 163 ++++------ crates/db_views/src/custom_emoji_view.rs | 12 +- crates/db_views/src/local_user_view.rs | 25 +- crates/db_views/src/post_report_view.rs | 73 ++--- crates/db_views/src/post_view.rs | 165 +++++----- .../src/private_message_report_view.rs | 50 ++- crates/db_views/src/private_message_view.rs | 23 +- .../src/registration_application_view.rs | 103 +++--- crates/db_views/src/site_view.rs | 6 +- .../db_views_actor/src/comment_reply_view.rs | 21 +- .../src/community_block_view.rs | 6 +- .../src/community_follower_view.rs | 12 +- .../src/community_moderator_view.rs | 15 +- .../src/community_person_ban_view.rs | 6 +- crates/db_views_actor/src/community_view.rs | 23 +- .../db_views_actor/src/person_block_view.rs | 6 +- .../db_views_actor/src/person_mention_view.rs | 20 +- crates/db_views_actor/src/person_view.rs | 20 +- .../src/admin_purge_comment_view.rs | 6 +- .../src/admin_purge_community_view.rs | 6 +- .../src/admin_purge_person_view.rs | 7 +- .../src/admin_purge_post_view.rs | 7 +- .../src/mod_add_community_view.rs | 6 +- crates/db_views_moderator/src/mod_add_view.rs | 6 +- .../src/mod_ban_from_community_view.rs | 7 +- crates/db_views_moderator/src/mod_ban_view.rs | 6 +- .../src/mod_feature_post_view.rs | 6 +- .../src/mod_hide_community_view.rs | 7 +- .../src/mod_lock_post_view.rs | 7 +- .../src/mod_remove_comment_view.rs | 6 +- .../src/mod_remove_community_view.rs | 6 +- .../src/mod_remove_post_view.rs | 7 +- .../src/mod_transfer_community_view.rs | 7 +- crates/routes/src/feeds.rs | 32 +- crates/routes/src/images.rs | 2 +- crates/routes/src/nodeinfo.rs | 2 +- crates/routes/src/webfinger.rs | 4 +- src/code_migrations.rs | 88 ++--- src/lib.rs | 8 +- 216 files changed, 2264 insertions(+), 2726 deletions(-) diff --git a/crates/api/src/comment/distinguish.rs b/crates/api/src/comment/distinguish.rs index a686bef78..17f45bfd4 100644 --- a/crates/api/src/comment/distinguish.rs +++ b/crates/api/src/comment/distinguish.rs @@ -22,18 +22,18 @@ impl Perform for DistinguishComment { let local_user_view = local_user_view_from_jwt(&data.auth, context).await?; let comment_id = data.comment_id; - let orig_comment = CommentView::read(context.conn().await?, comment_id, None).await?; + let orig_comment = CommentView::read(context.pool(), comment_id, None).await?; check_community_ban( local_user_view.person.id, orig_comment.community.id, - context.conn().await?, + context.pool(), ) .await?; // Verify that only a mod or admin can distinguish a comment is_mod_or_admin( - context.conn().await?, + context.pool(), local_user_view.person.id, orig_comment.community.id, ) @@ -44,14 +44,13 @@ impl Perform for DistinguishComment { let form = CommentUpdateForm::builder() .distinguished(Some(data.distinguished)) .build(); - Comment::update(context.conn().await?, comment_id, &form) + Comment::update(context.pool(), comment_id, &form) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?; let comment_id = data.comment_id; let person_id = local_user_view.person.id; - let comment_view = - CommentView::read(context.conn().await?, comment_id, Some(person_id)).await?; + let comment_view = CommentView::read(context.pool(), comment_id, Some(person_id)).await?; Ok(CommentResponse { comment_view, diff --git a/crates/api/src/comment/like.rs b/crates/api/src/comment/like.rs index 69e0d4b78..6c4bdebc7 100644 --- a/crates/api/src/comment/like.rs +++ b/crates/api/src/comment/like.rs @@ -25,7 +25,7 @@ impl Perform for CreateCommentLike { #[tracing::instrument(skip(context))] async fn perform(&self, context: &Data) -> Result { let data: &CreateCommentLike = self; - let local_site = LocalSite::read(context.conn().await?).await?; + let local_site = LocalSite::read(context.pool()).await?; let local_user_view = local_user_view_from_jwt(&data.auth, context).await?; let mut recipient_ids = Vec::::new(); @@ -34,22 +34,20 @@ impl Perform for CreateCommentLike { check_downvotes_enabled(data.score, &local_site)?; let comment_id = data.comment_id; - let orig_comment = CommentView::read(context.conn().await?, comment_id, None).await?; + let orig_comment = CommentView::read(context.pool(), comment_id, None).await?; check_community_ban( local_user_view.person.id, orig_comment.community.id, - context.conn().await?, + context.pool(), ) .await?; // Add parent poster or commenter to recipients - let comment_reply = CommentReply::read_by_comment(context.conn().await?, comment_id).await; + let comment_reply = CommentReply::read_by_comment(context.pool(), comment_id).await; if let Ok(reply) = comment_reply { let recipient_id = reply.recipient_id; - if let Ok(local_recipient) = - LocalUserView::read_person(context.conn().await?, recipient_id).await - { + if let Ok(local_recipient) = LocalUserView::read_person(context.pool(), recipient_id).await { recipient_ids.push(local_recipient.local_user.id); } } @@ -64,12 +62,12 @@ impl Perform for CreateCommentLike { // Remove any likes first let person_id = local_user_view.person.id; - CommentLike::remove(context.conn().await?, person_id, comment_id).await?; + CommentLike::remove(context.pool(), person_id, comment_id).await?; // Only add the like if the score isnt 0 let do_add = like_form.score != 0 && (like_form.score == 1 || like_form.score == -1); if do_add { - CommentLike::like(context.conn().await?, &like_form) + CommentLike::like(context.pool(), &like_form) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_like_comment"))?; } diff --git a/crates/api/src/comment/save.rs b/crates/api/src/comment/save.rs index 8fa0e8e4a..70c9745f8 100644 --- a/crates/api/src/comment/save.rs +++ b/crates/api/src/comment/save.rs @@ -27,19 +27,18 @@ impl Perform for SaveComment { }; if data.save { - CommentSaved::save(context.conn().await?, &comment_saved_form) + CommentSaved::save(context.pool(), &comment_saved_form) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_save_comment"))?; } else { - CommentSaved::unsave(context.conn().await?, &comment_saved_form) + CommentSaved::unsave(context.pool(), &comment_saved_form) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_save_comment"))?; } let comment_id = data.comment_id; let person_id = local_user_view.person.id; - let comment_view = - CommentView::read(context.conn().await?, comment_id, Some(person_id)).await?; + let comment_view = CommentView::read(context.pool(), comment_id, Some(person_id)).await?; Ok(CommentResponse { comment_view, diff --git a/crates/api/src/comment_report/create.rs b/crates/api/src/comment_report/create.rs index f5728ac93..8ef975786 100644 --- a/crates/api/src/comment_report/create.rs +++ b/crates/api/src/comment_report/create.rs @@ -27,16 +27,16 @@ impl Perform for CreateCommentReport { ) -> Result { let data: &CreateCommentReport = self; let local_user_view = local_user_view_from_jwt(&data.auth, context).await?; - let local_site = LocalSite::read(context.conn().await?).await?; + let local_site = LocalSite::read(context.pool()).await?; let reason = self.reason.trim(); check_report_reason(reason, &local_site)?; let person_id = local_user_view.person.id; let comment_id = data.comment_id; - let comment_view = CommentView::read(context.conn().await?, comment_id, None).await?; + let comment_view = CommentView::read(context.pool(), comment_id, None).await?; - check_community_ban(person_id, comment_view.community.id, context.conn().await?).await?; + check_community_ban(person_id, comment_view.community.id, context.pool()).await?; let report_form = CommentReportForm { creator_id: person_id, @@ -45,19 +45,18 @@ impl Perform for CreateCommentReport { reason: reason.to_owned(), }; - let report = CommentReport::report(context.conn().await?, &report_form) + let report = CommentReport::report(context.pool(), &report_form) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_create_report"))?; - let comment_report_view = - CommentReportView::read(context.conn().await?, report.id, person_id).await?; + let comment_report_view = CommentReportView::read(context.pool(), report.id, person_id).await?; // Email the admins if local_site.reports_email_admins { send_new_report_email_to_admins( &comment_report_view.creator.name, &comment_report_view.comment_creator.name, - context.conn().await?, + context.pool(), context.settings(), ) .await?; diff --git a/crates/api/src/comment_report/list.rs b/crates/api/src/comment_report/list.rs index 149e9b363..d8a4221db 100644 --- a/crates/api/src/comment_report/list.rs +++ b/crates/api/src/comment_report/list.rs @@ -30,7 +30,7 @@ impl Perform for ListCommentReports { let page = data.page; let limit = data.limit; let comment_reports = CommentReportQuery::builder() - .conn(context.conn().await?) + .pool(context.pool()) .my_person_id(person_id) .admin(admin) .community_id(community_id) diff --git a/crates/api/src/comment_report/resolve.rs b/crates/api/src/comment_report/resolve.rs index 5089403ea..5f1ae97dd 100644 --- a/crates/api/src/comment_report/resolve.rs +++ b/crates/api/src/comment_report/resolve.rs @@ -24,24 +24,23 @@ impl Perform for ResolveCommentReport { let report_id = data.report_id; let person_id = local_user_view.person.id; - let report = CommentReportView::read(context.conn().await?, report_id, person_id).await?; + let report = CommentReportView::read(context.pool(), report_id, person_id).await?; let person_id = local_user_view.person.id; - is_mod_or_admin(context.conn().await?, person_id, report.community.id).await?; + is_mod_or_admin(context.pool(), person_id, report.community.id).await?; if data.resolved { - CommentReport::resolve(context.conn().await?, report_id, person_id) + CommentReport::resolve(context.pool(), report_id, person_id) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_resolve_report"))?; } else { - CommentReport::unresolve(context.conn().await?, report_id, person_id) + CommentReport::unresolve(context.pool(), report_id, person_id) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_resolve_report"))?; } let report_id = data.report_id; - let comment_report_view = - CommentReportView::read(context.conn().await?, report_id, person_id).await?; + let comment_report_view = CommentReportView::read(context.pool(), report_id, person_id).await?; Ok(CommentReportResponse { comment_report_view, diff --git a/crates/api/src/community/add_mod.rs b/crates/api/src/community/add_mod.rs index b4a95dde6..a7afd952d 100644 --- a/crates/api/src/community/add_mod.rs +++ b/crates/api/src/community/add_mod.rs @@ -30,13 +30,8 @@ impl Perform for AddModToCommunity { let community_id = data.community_id; // Verify that only mods or admins can add mod - is_mod_or_admin( - context.conn().await?, - local_user_view.person.id, - community_id, - ) - .await?; - let community = Community::read(context.conn().await?, community_id).await?; + is_mod_or_admin(context.pool(), local_user_view.person.id, community_id).await?; + let community = Community::read(context.pool(), community_id).await?; if local_user_view.person.admin && !community.local { return Err(LemmyError::from_message("not_a_moderator")); } @@ -47,11 +42,11 @@ impl Perform for AddModToCommunity { person_id: data.person_id, }; if data.added { - CommunityModerator::join(context.conn().await?, &community_moderator_form) + CommunityModerator::join(context.pool(), &community_moderator_form) .await .map_err(|e| LemmyError::from_error_message(e, "community_moderator_already_exists"))?; } else { - CommunityModerator::leave(context.conn().await?, &community_moderator_form) + CommunityModerator::leave(context.pool(), &community_moderator_form) .await .map_err(|e| LemmyError::from_error_message(e, "community_moderator_already_exists"))?; } @@ -64,13 +59,12 @@ impl Perform for AddModToCommunity { removed: Some(!data.added), }; - ModAddCommunity::create(context.conn().await?, &form).await?; + ModAddCommunity::create(context.pool(), &form).await?; // Note: in case a remote mod is added, this returns the old moderators list, it will only get // updated once we receive an activity from the community (like `Announce/Add/Moderator`) let community_id = data.community_id; - let moderators = - CommunityModeratorView::for_community(context.conn().await?, community_id).await?; + let moderators = CommunityModeratorView::for_community(context.pool(), community_id).await?; Ok(AddModToCommunityResponse { moderators }) } diff --git a/crates/api/src/community/ban.rs b/crates/api/src/community/ban.rs index 267ee8a25..330c2c56d 100644 --- a/crates/api/src/community/ban.rs +++ b/crates/api/src/community/ban.rs @@ -41,12 +41,7 @@ impl Perform for BanFromCommunity { let expires = data.expires.map(naive_from_unix); // Verify that only mods or admins can ban - is_mod_or_admin( - context.conn().await?, - local_user_view.person.id, - community_id, - ) - .await?; + is_mod_or_admin(context.pool(), local_user_view.person.id, community_id).await?; is_valid_body_field(&data.reason, false)?; let community_user_ban_form = CommunityPersonBanForm { @@ -56,7 +51,7 @@ impl Perform for BanFromCommunity { }; if data.ban { - CommunityPersonBan::ban(context.conn().await?, &community_user_ban_form) + CommunityPersonBan::ban(context.pool(), &community_user_ban_form) .await .map_err(|e| LemmyError::from_error_message(e, "community_user_already_banned"))?; @@ -67,11 +62,11 @@ impl Perform for BanFromCommunity { pending: false, }; - CommunityFollower::unfollow(context.conn().await?, &community_follower_form) + CommunityFollower::unfollow(context.pool(), &community_follower_form) .await .ok(); } else { - CommunityPersonBan::unban(context.conn().await?, &community_user_ban_form) + CommunityPersonBan::unban(context.pool(), &community_user_ban_form) .await .map_err(|e| LemmyError::from_error_message(e, "community_user_already_banned"))?; } @@ -91,10 +86,10 @@ impl Perform for BanFromCommunity { expires, }; - ModBanFromCommunity::create(context.conn().await?, &form).await?; + ModBanFromCommunity::create(context.pool(), &form).await?; let person_id = data.person_id; - let person_view = PersonView::read(context.conn().await?, person_id).await?; + let person_view = PersonView::read(context.pool(), person_id).await?; Ok(BanFromCommunityResponse { person_view, diff --git a/crates/api/src/community/block.rs b/crates/api/src/community/block.rs index e9e09d90a..fe3fb6e07 100644 --- a/crates/api/src/community/block.rs +++ b/crates/api/src/community/block.rs @@ -35,7 +35,7 @@ impl Perform for BlockCommunity { }; if data.block { - CommunityBlock::block(context.conn().await?, &community_block_form) + CommunityBlock::block(context.pool(), &community_block_form) .await .map_err(|e| LemmyError::from_error_message(e, "community_block_already_exists"))?; @@ -46,17 +46,17 @@ impl Perform for BlockCommunity { pending: false, }; - CommunityFollower::unfollow(context.conn().await?, &community_follower_form) + CommunityFollower::unfollow(context.pool(), &community_follower_form) .await .ok(); } else { - CommunityBlock::unblock(context.conn().await?, &community_block_form) + CommunityBlock::unblock(context.pool(), &community_block_form) .await .map_err(|e| LemmyError::from_error_message(e, "community_block_already_exists"))?; } let community_view = - CommunityView::read(context.conn().await?, community_id, Some(person_id), None).await?; + CommunityView::read(context.pool(), community_id, Some(person_id), None).await?; Ok(BlockCommunityResponse { blocked: data.block, diff --git a/crates/api/src/community/follow.rs b/crates/api/src/community/follow.rs index 30958299d..39feeff25 100644 --- a/crates/api/src/community/follow.rs +++ b/crates/api/src/community/follow.rs @@ -25,7 +25,7 @@ impl Perform for FollowCommunity { let local_user_view = local_user_view_from_jwt(&data.auth, context).await?; let community_id = data.community_id; - let community = Community::read(context.conn().await?, community_id).await?; + let community = Community::read(context.pool(), community_id).await?; let mut community_follower_form = CommunityFollowerForm { community_id: data.community_id, person_id: local_user_view.person.id, @@ -34,27 +34,22 @@ impl Perform for FollowCommunity { if data.follow { if community.local { - check_community_ban( - local_user_view.person.id, - community_id, - context.conn().await?, - ) - .await?; - check_community_deleted_or_removed(community_id, context.conn().await?).await?; + check_community_ban(local_user_view.person.id, community_id, context.pool()).await?; + check_community_deleted_or_removed(community_id, context.pool()).await?; - CommunityFollower::follow(context.conn().await?, &community_follower_form) + CommunityFollower::follow(context.pool(), &community_follower_form) .await .map_err(|e| LemmyError::from_error_message(e, "community_follower_already_exists"))?; } else { // Mark as pending, the actual federation activity is sent via `SendActivity` handler community_follower_form.pending = true; - CommunityFollower::follow(context.conn().await?, &community_follower_form) + CommunityFollower::follow(context.pool(), &community_follower_form) .await .map_err(|e| LemmyError::from_error_message(e, "community_follower_already_exists"))?; } } if !data.follow { - CommunityFollower::unfollow(context.conn().await?, &community_follower_form) + CommunityFollower::unfollow(context.pool(), &community_follower_form) .await .map_err(|e| LemmyError::from_error_message(e, "community_follower_already_exists"))?; } @@ -62,8 +57,8 @@ impl Perform for FollowCommunity { let community_id = data.community_id; let person_id = local_user_view.person.id; let community_view = - CommunityView::read(context.conn().await?, community_id, Some(person_id), None).await?; - let discussion_languages = CommunityLanguage::read(context.conn().await?, community_id).await?; + CommunityView::read(context.pool(), community_id, Some(person_id), None).await?; + let discussion_languages = CommunityLanguage::read(context.pool(), community_id).await?; Ok(Self::Response { community_view, diff --git a/crates/api/src/community/hide.rs b/crates/api/src/community/hide.rs index 61c7b4f85..f8d4b1fd7 100644 --- a/crates/api/src/community/hide.rs +++ b/crates/api/src/community/hide.rs @@ -39,11 +39,11 @@ impl Perform for HideCommunity { }; let community_id = data.community_id; - Community::update(context.conn().await?, community_id, &community_form) + Community::update(context.pool(), community_id, &community_form) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_community_hidden_status"))?; - ModHideCommunity::create(context.conn().await?, &mod_hide_community_form).await?; + ModHideCommunity::create(context.pool(), &mod_hide_community_form).await?; build_community_response(context, local_user_view, community_id).await } diff --git a/crates/api/src/community/transfer.rs b/crates/api/src/community/transfer.rs index 13b2cdfab..10ba1c4fa 100644 --- a/crates/api/src/community/transfer.rs +++ b/crates/api/src/community/transfer.rs @@ -33,7 +33,7 @@ impl Perform for TransferCommunity { // Fetch the community mods let community_id = data.community_id; let mut community_mods = - CommunityModeratorView::for_community(context.conn().await?, community_id).await?; + CommunityModeratorView::for_community(context.pool(), community_id).await?; // Make sure transferrer is either the top community mod, or an admin if !(is_top_mod(&local_user_view, &community_mods).is_ok() @@ -54,7 +54,7 @@ impl Perform for TransferCommunity { // Delete all the mods let community_id = data.community_id; - CommunityModerator::delete_for_community(context.conn().await?, community_id).await?; + CommunityModerator::delete_for_community(context.pool(), community_id).await?; // TODO: this should probably be a bulk operation // Re-add the mods, in the new order @@ -64,7 +64,7 @@ impl Perform for TransferCommunity { person_id: cmod.moderator.id, }; - CommunityModerator::join(context.conn().await?, &community_moderator_form) + CommunityModerator::join(context.pool(), &community_moderator_form) .await .map_err(|e| LemmyError::from_error_message(e, "community_moderator_already_exists"))?; } @@ -76,17 +76,16 @@ impl Perform for TransferCommunity { community_id: data.community_id, }; - ModTransferCommunity::create(context.conn().await?, &form).await?; + ModTransferCommunity::create(context.pool(), &form).await?; let community_id = data.community_id; let person_id = local_user_view.person.id; - let community_view = - CommunityView::read(context.conn().await?, community_id, Some(person_id), None) - .await - .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?; + let community_view = CommunityView::read(context.pool(), community_id, Some(person_id), None) + .await + .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?; let community_id = data.community_id; - let moderators = CommunityModeratorView::for_community(context.conn().await?, community_id) + let moderators = CommunityModeratorView::for_community(context.pool(), community_id) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?; diff --git a/crates/api/src/lib.rs b/crates/api/src/lib.rs index 80cbe2869..7ac3cec72 100644 --- a/crates/api/src/lib.rs +++ b/crates/api/src/lib.rs @@ -86,7 +86,7 @@ mod tests { secret::Secret, }, traits::Crud, - utils::build_db_conn_for_tests, + utils::build_db_pool_for_tests, }; use lemmy_utils::{claims::Claims, settings::SETTINGS}; use serial_test::serial; @@ -94,11 +94,11 @@ mod tests { #[tokio::test] #[serial] async fn test_should_not_validate_user_token_after_password_change() { - let mut conn = build_db_conn_for_tests().await; - let secret = Secret::init(conn).await.unwrap(); + let pool = &build_db_pool_for_tests().await; + let secret = Secret::init(pool).await.unwrap(); let settings = &SETTINGS.to_owned(); - let inserted_instance = Instance::read_or_create(conn, "my_domain.tld".to_string()) + let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()) .await .unwrap(); @@ -108,16 +108,14 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_person = Person::create(conn, &new_person).await.unwrap(); + let inserted_person = Person::create(pool, &new_person).await.unwrap(); let local_user_form = LocalUserInsertForm::builder() .person_id(inserted_person.id) .password_encrypted("123456".to_string()) .build(); - let inserted_local_user = LocalUser::create(conn, &local_user_form) - .await - .unwrap(); + let inserted_local_user = LocalUser::create(pool, &local_user_form).await.unwrap(); let jwt = Claims::jwt( inserted_local_user.id.0, @@ -131,15 +129,13 @@ mod tests { // The check should fail, since the validator time is now newer than the jwt issue time let updated_local_user = - LocalUser::update_password(conn, inserted_local_user.id, "password111") + LocalUser::update_password(pool, inserted_local_user.id, "password111") .await .unwrap(); let check_after = check_validator_time(&updated_local_user.validator_time, &claims); assert!(check_after.is_err()); - let num_deleted = Person::delete(conn, inserted_person.id) - .await - .unwrap(); + let num_deleted = Person::delete(pool, inserted_person.id).await.unwrap(); assert_eq!(1, num_deleted); } } diff --git a/crates/api/src/local_user/add_admin.rs b/crates/api/src/local_user/add_admin.rs index 386ca0631..0d2db3771 100644 --- a/crates/api/src/local_user/add_admin.rs +++ b/crates/api/src/local_user/add_admin.rs @@ -30,7 +30,7 @@ impl Perform for AddAdmin { let added = data.added; let added_person_id = data.person_id; let added_admin = Person::update( - context.conn().await?, + context.pool(), added_person_id, &PersonUpdateForm::builder().admin(Some(added)).build(), ) @@ -44,9 +44,9 @@ impl Perform for AddAdmin { removed: Some(!data.added), }; - ModAdd::create(context.conn().await?, &form).await?; + ModAdd::create(context.pool(), &form).await?; - let admins = PersonView::admins(context.conn().await?).await?; + let admins = PersonView::admins(context.pool()).await?; Ok(AddAdminResponse { admins }) } diff --git a/crates/api/src/local_user/ban_person.rs b/crates/api/src/local_user/ban_person.rs index 79ed82c76..2c2d363e3 100644 --- a/crates/api/src/local_user/ban_person.rs +++ b/crates/api/src/local_user/ban_person.rs @@ -37,7 +37,7 @@ impl Perform for BanPerson { let expires = data.expires.map(naive_from_unix); let person = Person::update( - context.conn().await?, + context.pool(), banned_person_id, &PersonUpdateForm::builder() .banned(Some(ban)) @@ -68,10 +68,10 @@ impl Perform for BanPerson { expires, }; - ModBan::create(context.conn().await?, &form).await?; + ModBan::create(context.pool(), &form).await?; let person_id = data.person_id; - let person_view = PersonView::read(context.conn().await?, person_id).await?; + let person_view = PersonView::read(context.pool(), person_id).await?; Ok(BanPersonResponse { person_view, diff --git a/crates/api/src/local_user/block.rs b/crates/api/src/local_user/block.rs index d9eb1b72f..c9eaa2725 100644 --- a/crates/api/src/local_user/block.rs +++ b/crates/api/src/local_user/block.rs @@ -34,18 +34,18 @@ impl Perform for BlockPerson { target_id, }; - let target_person_view = PersonView::read(context.conn().await?, target_id).await?; + let target_person_view = PersonView::read(context.pool(), target_id).await?; if target_person_view.person.admin { return Err(LemmyError::from_message("cant_block_admin")); } if data.block { - PersonBlock::block(context.conn().await?, &person_block_form) + PersonBlock::block(context.pool(), &person_block_form) .await .map_err(|e| LemmyError::from_error_message(e, "person_block_already_exists"))?; } else { - PersonBlock::unblock(context.conn().await?, &person_block_form) + PersonBlock::unblock(context.pool(), &person_block_form) .await .map_err(|e| LemmyError::from_error_message(e, "person_block_already_exists"))?; } diff --git a/crates/api/src/local_user/change_password.rs b/crates/api/src/local_user/change_password.rs index 30d6a4986..60e0b960d 100644 --- a/crates/api/src/local_user/change_password.rs +++ b/crates/api/src/local_user/change_password.rs @@ -38,7 +38,7 @@ impl Perform for ChangePassword { let local_user_id = local_user_view.local_user.id; let new_password = data.new_password.clone(); let updated_local_user = - LocalUser::update_password(context.conn().await?, local_user_id, &new_password).await?; + LocalUser::update_password(context.pool(), local_user_id, &new_password).await?; // Return the jwt Ok(LoginResponse { diff --git a/crates/api/src/local_user/change_password_after_reset.rs b/crates/api/src/local_user/change_password_after_reset.rs index afa9b550b..de05f8e59 100644 --- a/crates/api/src/local_user/change_password_after_reset.rs +++ b/crates/api/src/local_user/change_password_after_reset.rs @@ -22,7 +22,7 @@ impl Perform for PasswordChangeAfterReset { // Fetch the user_id from the token let token = data.token.clone(); - let local_user_id = PasswordResetRequest::read_from_token(context.conn().await?, &token) + let local_user_id = PasswordResetRequest::read_from_token(context.pool(), &token) .await .map(|p| p.local_user_id)?; @@ -35,13 +35,12 @@ impl Perform for PasswordChangeAfterReset { // Update the user with the new password let password = data.password.clone(); - let updated_local_user = - LocalUser::update_password(context.conn().await?, local_user_id, &password) - .await - .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_user"))?; + let updated_local_user = LocalUser::update_password(context.pool(), local_user_id, &password) + .await + .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_user"))?; // Return the jwt if login is allowed - let site_view = SiteView::read_local(context.conn().await?).await?; + let site_view = SiteView::read_local(context.pool()).await?; let jwt = if site_view.local_site.registration_mode == RegistrationMode::RequireApplication && !updated_local_user.accepted_application { diff --git a/crates/api/src/local_user/get_captcha.rs b/crates/api/src/local_user/get_captcha.rs index 52fd5bda6..92653cfc6 100644 --- a/crates/api/src/local_user/get_captcha.rs +++ b/crates/api/src/local_user/get_captcha.rs @@ -17,7 +17,7 @@ impl Perform for GetCaptcha { #[tracing::instrument(skip(context))] async fn perform(&self, context: &Data) -> Result { - let local_site = LocalSite::read(context.conn().await?).await?; + let local_site = LocalSite::read(context.pool()).await?; if !local_site.captcha_enabled { return Ok(GetCaptchaResponse { ok: None }); @@ -37,7 +37,7 @@ impl Perform for GetCaptcha { let captcha_form: CaptchaAnswerForm = CaptchaAnswerForm { answer }; // Stores the captcha item in the db - let captcha = CaptchaAnswer::insert(context.conn().await?, &captcha_form).await?; + let captcha = CaptchaAnswer::insert(context.pool(), &captcha_form).await?; Ok(GetCaptchaResponse { ok: Some(CaptchaResponse { diff --git a/crates/api/src/local_user/list_banned.rs b/crates/api/src/local_user/list_banned.rs index 1ecb0845f..5e2c027ba 100644 --- a/crates/api/src/local_user/list_banned.rs +++ b/crates/api/src/local_user/list_banned.rs @@ -19,7 +19,7 @@ impl Perform for GetBannedPersons { // Make sure user is an admin is_admin(&local_user_view)?; - let banned = PersonView::banned(context.conn().await?).await?; + let banned = PersonView::banned(context.pool()).await?; Ok(Self::Response { banned }) } diff --git a/crates/api/src/local_user/login.rs b/crates/api/src/local_user/login.rs index 99e910a43..9e211c9c4 100644 --- a/crates/api/src/local_user/login.rs +++ b/crates/api/src/local_user/login.rs @@ -17,14 +17,13 @@ impl Perform for Login { async fn perform(&self, context: &Data) -> Result { let data: &Login = self; - let site_view = SiteView::read_local(context.conn().await?).await?; + let site_view = SiteView::read_local(context.pool()).await?; // Fetch that username / email let username_or_email = data.username_or_email.clone(); - let local_user_view = - LocalUserView::find_by_email_or_name(context.conn().await?, &username_or_email) - .await - .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_that_username_or_email"))?; + let local_user_view = LocalUserView::find_by_email_or_name(context.pool(), &username_or_email) + .await + .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_that_username_or_email"))?; // Verify the password let valid: bool = verify( @@ -50,12 +49,7 @@ impl Perform for Login { return Err(LemmyError::from_message("email_not_verified")); } - check_registration_application( - &local_user_view, - &site_view.local_site, - context.conn().await?, - ) - .await?; + check_registration_application(&local_user_view, &site_view.local_site, context.pool()).await?; // Check the totp check_totp_2fa_valid( diff --git a/crates/api/src/local_user/notifications/list_mentions.rs b/crates/api/src/local_user/notifications/list_mentions.rs index d7d1c516f..4c8d2cf55 100644 --- a/crates/api/src/local_user/notifications/list_mentions.rs +++ b/crates/api/src/local_user/notifications/list_mentions.rs @@ -28,7 +28,7 @@ impl Perform for GetPersonMentions { let show_bot_accounts = Some(local_user_view.local_user.show_bot_accounts); let mentions = PersonMentionQuery::builder() - .conn(context.conn().await?) + .pool(context.pool()) .recipient_id(person_id) .my_person_id(person_id) .sort(sort) diff --git a/crates/api/src/local_user/notifications/list_replies.rs b/crates/api/src/local_user/notifications/list_replies.rs index 6e7e2034d..6d1d8f0bd 100644 --- a/crates/api/src/local_user/notifications/list_replies.rs +++ b/crates/api/src/local_user/notifications/list_replies.rs @@ -25,7 +25,7 @@ impl Perform for GetReplies { let show_bot_accounts = Some(local_user_view.local_user.show_bot_accounts); let replies = CommentReplyQuery::builder() - .conn(context.conn().await?) + .pool(context.pool()) .recipient_id(person_id) .my_person_id(person_id) .sort(sort) diff --git a/crates/api/src/local_user/notifications/mark_all_read.rs b/crates/api/src/local_user/notifications/mark_all_read.rs index 358135aeb..cc2999698 100644 --- a/crates/api/src/local_user/notifications/mark_all_read.rs +++ b/crates/api/src/local_user/notifications/mark_all_read.rs @@ -23,17 +23,17 @@ impl Perform for MarkAllAsRead { let person_id = local_user_view.person.id; // Mark all comment_replies as read - CommentReply::mark_all_as_read(context.conn().await?, person_id) + CommentReply::mark_all_as_read(context.pool(), person_id) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?; // Mark all user mentions as read - PersonMention::mark_all_as_read(context.conn().await?, person_id) + PersonMention::mark_all_as_read(context.pool(), person_id) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?; // Mark all private_messages as read - PrivateMessage::mark_all_as_read(context.conn().await?, person_id) + PrivateMessage::mark_all_as_read(context.pool(), person_id) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_private_message"))?; diff --git a/crates/api/src/local_user/notifications/mark_mention_read.rs b/crates/api/src/local_user/notifications/mark_mention_read.rs index 895c84b83..dd3c413f2 100644 --- a/crates/api/src/local_user/notifications/mark_mention_read.rs +++ b/crates/api/src/local_user/notifications/mark_mention_read.rs @@ -25,7 +25,7 @@ impl Perform for MarkPersonMentionAsRead { let local_user_view = local_user_view_from_jwt(&data.auth, context).await?; let person_mention_id = data.person_mention_id; - let read_person_mention = PersonMention::read(context.conn().await?, person_mention_id).await?; + let read_person_mention = PersonMention::read(context.pool(), person_mention_id).await?; if local_user_view.person.id != read_person_mention.recipient_id { return Err(LemmyError::from_message("couldnt_update_comment")); @@ -34,7 +34,7 @@ impl Perform for MarkPersonMentionAsRead { let person_mention_id = read_person_mention.id; let read = Some(data.read); PersonMention::update( - context.conn().await?, + context.pool(), person_mention_id, &PersonMentionUpdateForm { read }, ) @@ -44,7 +44,7 @@ impl Perform for MarkPersonMentionAsRead { let person_mention_id = read_person_mention.id; let person_id = local_user_view.person.id; let person_mention_view = - PersonMentionView::read(context.conn().await?, person_mention_id, Some(person_id)).await?; + PersonMentionView::read(context.pool(), person_mention_id, Some(person_id)).await?; Ok(PersonMentionResponse { person_mention_view, diff --git a/crates/api/src/local_user/notifications/mark_reply_read.rs b/crates/api/src/local_user/notifications/mark_reply_read.rs index 70d7f8fe6..a8291cd50 100644 --- a/crates/api/src/local_user/notifications/mark_reply_read.rs +++ b/crates/api/src/local_user/notifications/mark_reply_read.rs @@ -25,7 +25,7 @@ impl Perform for MarkCommentReplyAsRead { let local_user_view = local_user_view_from_jwt(&data.auth, context).await?; let comment_reply_id = data.comment_reply_id; - let read_comment_reply = CommentReply::read(context.conn().await?, comment_reply_id).await?; + let read_comment_reply = CommentReply::read(context.pool(), comment_reply_id).await?; if local_user_view.person.id != read_comment_reply.recipient_id { return Err(LemmyError::from_message("couldnt_update_comment")); @@ -35,7 +35,7 @@ impl Perform for MarkCommentReplyAsRead { let read = Some(data.read); CommentReply::update( - context.conn().await?, + context.pool(), comment_reply_id, &CommentReplyUpdateForm { read }, ) @@ -45,7 +45,7 @@ impl Perform for MarkCommentReplyAsRead { let comment_reply_id = read_comment_reply.id; let person_id = local_user_view.person.id; let comment_reply_view = - CommentReplyView::read(context.conn().await?, comment_reply_id, Some(person_id)).await?; + CommentReplyView::read(context.pool(), comment_reply_id, Some(person_id)).await?; Ok(CommentReplyResponse { comment_reply_view }) } diff --git a/crates/api/src/local_user/notifications/unread_count.rs b/crates/api/src/local_user/notifications/unread_count.rs index db66e298c..21e584d51 100644 --- a/crates/api/src/local_user/notifications/unread_count.rs +++ b/crates/api/src/local_user/notifications/unread_count.rs @@ -20,12 +20,12 @@ impl Perform for GetUnreadCount { let person_id = local_user_view.person.id; - let replies = CommentReplyView::get_unread_replies(context.conn().await?, person_id).await?; + let replies = CommentReplyView::get_unread_replies(context.pool(), person_id).await?; - let mentions = PersonMentionView::get_unread_mentions(context.conn().await?, person_id).await?; + let mentions = PersonMentionView::get_unread_mentions(context.pool(), person_id).await?; let private_messages = - PrivateMessageView::get_unread_messages(context.conn().await?, person_id).await?; + PrivateMessageView::get_unread_messages(context.pool(), person_id).await?; Ok(Self::Response { replies, diff --git a/crates/api/src/local_user/report_count.rs b/crates/api/src/local_user/report_count.rs index 25a803cf2..c09280d80 100644 --- a/crates/api/src/local_user/report_count.rs +++ b/crates/api/src/local_user/report_count.rs @@ -25,15 +25,13 @@ impl Perform for GetReportCount { let community_id = data.community_id; let comment_reports = - CommentReportView::get_report_count(context.conn().await?, person_id, admin, community_id) - .await?; + CommentReportView::get_report_count(context.pool(), person_id, admin, community_id).await?; let post_reports = - PostReportView::get_report_count(context.conn().await?, person_id, admin, community_id) - .await?; + PostReportView::get_report_count(context.pool(), person_id, admin, community_id).await?; let private_message_reports = if admin && community_id.is_none() { - Some(PrivateMessageReportView::get_report_count(context.conn().await?).await?) + Some(PrivateMessageReportView::get_report_count(context.pool()).await?) } else { None }; diff --git a/crates/api/src/local_user/reset_password.rs b/crates/api/src/local_user/reset_password.rs index 7ba7b8aac..b5325608d 100644 --- a/crates/api/src/local_user/reset_password.rs +++ b/crates/api/src/local_user/reset_password.rs @@ -22,13 +22,13 @@ impl Perform for PasswordReset { // Fetch that email let email = data.email.to_lowercase(); - let local_user_view = LocalUserView::find_by_email(context.conn().await?, &email) + let local_user_view = LocalUserView::find_by_email(context.pool(), &email) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_that_username_or_email"))?; // Check for too many attempts (to limit potential abuse) let recent_resets_count = PasswordResetRequest::get_recent_password_resets_count( - context.conn().await?, + context.pool(), local_user_view.local_user.id, ) .await?; @@ -37,7 +37,7 @@ impl Perform for PasswordReset { } // Email the pure token to the user. - send_password_reset_email(&local_user_view, context.conn().await?, context.settings()).await?; + send_password_reset_email(&local_user_view, context.pool(), context.settings()).await?; Ok(PasswordResetResponse {}) } } diff --git a/crates/api/src/local_user/save_settings.rs b/crates/api/src/local_user/save_settings.rs index 5e4548dd6..8f8d3194e 100644 --- a/crates/api/src/local_user/save_settings.rs +++ b/crates/api/src/local_user/save_settings.rs @@ -35,7 +35,7 @@ impl Perform for SaveUserSettings { async fn perform(&self, context: &Data) -> Result { let data: &SaveUserSettings = self; let local_user_view = local_user_view_from_jwt(&data.auth, context).await?; - let site_view = SiteView::read_local(context.conn().await?).await?; + let site_view = SiteView::read_local(context.pool()).await?; let avatar = diesel_option_overwrite_to_url(&data.avatar)?; let banner = diesel_option_overwrite_to_url(&data.banner)?; @@ -49,13 +49,8 @@ impl Perform for SaveUserSettings { let previous_email = local_user_view.local_user.email.clone().unwrap_or_default(); // Only send the verification email if there was an email change if previous_email.ne(email) { - send_verification_email( - &local_user_view, - email, - context.conn().await?, - context.settings(), - ) - .await?; + send_verification_email(&local_user_view, email, context.pool(), context.settings()) + .await?; } } @@ -95,12 +90,12 @@ impl Perform for SaveUserSettings { .banner(banner) .build(); - Person::update(context.conn().await?, person_id, &person_form) + Person::update(context.pool(), person_id, &person_form) .await .map_err(|e| LemmyError::from_error_message(e, "user_already_exists"))?; if let Some(discussion_languages) = data.discussion_languages.clone() { - LocalUserLanguage::update(context.conn().await?, discussion_languages, local_user_id).await?; + LocalUserLanguage::update(context.pool(), discussion_languages, local_user_id).await?; } // If generate_totp is Some(false), this will clear it out from the database. @@ -135,8 +130,7 @@ impl Perform for SaveUserSettings { .open_links_in_new_tab(data.open_links_in_new_tab) .build(); - let local_user_res = - LocalUser::update(context.conn().await?, local_user_id, &local_user_form).await; + let local_user_res = LocalUser::update(context.pool(), local_user_id, &local_user_form).await; let updated_local_user = match local_user_res { Ok(u) => u, Err(e) => { diff --git a/crates/api/src/local_user/verify_email.rs b/crates/api/src/local_user/verify_email.rs index fd3f8f6ee..0807eebe0 100644 --- a/crates/api/src/local_user/verify_email.rs +++ b/crates/api/src/local_user/verify_email.rs @@ -19,7 +19,7 @@ impl Perform for VerifyEmail { async fn perform(&self, context: &Data) -> Result { let token = self.token.clone(); - let verification = EmailVerification::read_for_token(context.conn().await?, &token) + let verification = EmailVerification::read_for_token(context.pool(), &token) .await .map_err(|e| LemmyError::from_error_message(e, "token_not_found"))?; @@ -31,10 +31,9 @@ impl Perform for VerifyEmail { .build(); let local_user_id = verification.local_user_id; - LocalUser::update(context.conn().await?, local_user_id, &form).await?; + LocalUser::update(context.pool(), local_user_id, &form).await?; - EmailVerification::delete_old_tokens_for_local_user(context.conn().await?, local_user_id) - .await?; + EmailVerification::delete_old_tokens_for_local_user(context.pool(), local_user_id).await?; Ok(VerifyEmailResponse {}) } diff --git a/crates/api/src/post/feature.rs b/crates/api/src/post/feature.rs index ac277264d..3c9e1a1c0 100644 --- a/crates/api/src/post/feature.rs +++ b/crates/api/src/post/feature.rs @@ -32,20 +32,20 @@ impl Perform for FeaturePost { let local_user_view = local_user_view_from_jwt(&data.auth, context).await?; let post_id = data.post_id; - let orig_post = Post::read(context.conn().await?, post_id).await?; + let orig_post = Post::read(context.pool(), post_id).await?; check_community_ban( local_user_view.person.id, orig_post.community_id, - context.conn().await?, + context.pool(), ) .await?; - check_community_deleted_or_removed(orig_post.community_id, context.conn().await?).await?; + check_community_deleted_or_removed(orig_post.community_id, context.pool()).await?; if data.feature_type == PostFeatureType::Community { // Verify that only the mods can feature in community is_mod_or_admin( - context.conn().await?, + context.pool(), local_user_view.person.id, orig_post.community_id, ) @@ -65,7 +65,7 @@ impl Perform for FeaturePost { .featured_local(Some(data.featured)) .build() }; - Post::update(context.conn().await?, post_id, &new_post).await?; + Post::update(context.pool(), post_id, &new_post).await?; // Mod tables let form = ModFeaturePostForm { @@ -75,7 +75,7 @@ impl Perform for FeaturePost { is_featured_community: data.feature_type == PostFeatureType::Community, }; - ModFeaturePost::create(context.conn().await?, &form).await?; + ModFeaturePost::create(context.pool(), &form).await?; build_post_response( context, diff --git a/crates/api/src/post/like.rs b/crates/api/src/post/like.rs index 3b1f528b9..5811107c2 100644 --- a/crates/api/src/post/like.rs +++ b/crates/api/src/post/like.rs @@ -29,22 +29,17 @@ impl Perform for CreatePostLike { async fn perform(&self, context: &Data) -> Result { let data: &CreatePostLike = self; let local_user_view = local_user_view_from_jwt(&data.auth, context).await?; - let local_site = LocalSite::read(context.conn().await?).await?; + let local_site = LocalSite::read(context.pool()).await?; // Don't do a downvote if site has downvotes disabled check_downvotes_enabled(data.score, &local_site)?; // Check for a community ban let post_id = data.post_id; - let post = Post::read(context.conn().await?, post_id).await?; + let post = Post::read(context.pool(), post_id).await?; - check_community_ban( - local_user_view.person.id, - post.community_id, - context.conn().await?, - ) - .await?; - check_community_deleted_or_removed(post.community_id, context.conn().await?).await?; + check_community_ban(local_user_view.person.id, post.community_id, context.pool()).await?; + check_community_deleted_or_removed(post.community_id, context.pool()).await?; let like_form = PostLikeForm { post_id: data.post_id, @@ -55,18 +50,18 @@ impl Perform for CreatePostLike { // Remove any likes first let person_id = local_user_view.person.id; - PostLike::remove(context.conn().await?, person_id, post_id).await?; + PostLike::remove(context.pool(), person_id, post_id).await?; // Only add the like if the score isnt 0 let do_add = like_form.score != 0 && (like_form.score == 1 || like_form.score == -1); if do_add { - PostLike::like(context.conn().await?, &like_form) + PostLike::like(context.pool(), &like_form) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_like_post"))?; } // Mark the post as read - mark_post_as_read(person_id, post_id, context.conn().await?).await?; + mark_post_as_read(person_id, post_id, context.pool()).await?; build_post_response( context, diff --git a/crates/api/src/post/lock.rs b/crates/api/src/post/lock.rs index 88d91cf7f..5266d5441 100644 --- a/crates/api/src/post/lock.rs +++ b/crates/api/src/post/lock.rs @@ -30,19 +30,19 @@ impl Perform for LockPost { let local_user_view = local_user_view_from_jwt(&data.auth, context).await?; let post_id = data.post_id; - let orig_post = Post::read(context.conn().await?, post_id).await?; + let orig_post = Post::read(context.pool(), post_id).await?; check_community_ban( local_user_view.person.id, orig_post.community_id, - context.conn().await?, + context.pool(), ) .await?; - check_community_deleted_or_removed(orig_post.community_id, context.conn().await?).await?; + check_community_deleted_or_removed(orig_post.community_id, context.pool()).await?; // Verify that only the mods can lock is_mod_or_admin( - context.conn().await?, + context.pool(), local_user_view.person.id, orig_post.community_id, ) @@ -52,7 +52,7 @@ impl Perform for LockPost { let post_id = data.post_id; let locked = data.locked; Post::update( - context.conn().await?, + context.pool(), post_id, &PostUpdateForm::builder().locked(Some(locked)).build(), ) @@ -64,7 +64,7 @@ impl Perform for LockPost { post_id: data.post_id, locked: Some(locked), }; - ModLockPost::create(context.conn().await?, &form).await?; + ModLockPost::create(context.pool(), &form).await?; build_post_response( context, diff --git a/crates/api/src/post/mark_read.rs b/crates/api/src/post/mark_read.rs index 491e2a104..0e013a883 100644 --- a/crates/api/src/post/mark_read.rs +++ b/crates/api/src/post/mark_read.rs @@ -22,13 +22,13 @@ impl Perform for MarkPostAsRead { // Mark the post as read / unread if data.read { - mark_post_as_read(person_id, post_id, context.conn().await?).await?; + mark_post_as_read(person_id, post_id, context.pool()).await?; } else { - mark_post_as_unread(person_id, post_id, context.conn().await?).await?; + mark_post_as_unread(person_id, post_id, context.pool()).await?; } // Fetch it - let post_view = PostView::read(context.conn().await?, post_id, Some(person_id), None).await?; + let post_view = PostView::read(context.pool(), post_id, Some(person_id), None).await?; Ok(Self::Response { post_view }) } diff --git a/crates/api/src/post/save.rs b/crates/api/src/post/save.rs index 2b6d06889..3213d2be6 100644 --- a/crates/api/src/post/save.rs +++ b/crates/api/src/post/save.rs @@ -27,21 +27,21 @@ impl Perform for SavePost { }; if data.save { - PostSaved::save(context.conn().await?, &post_saved_form) + PostSaved::save(context.pool(), &post_saved_form) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_save_post"))?; } else { - PostSaved::unsave(context.conn().await?, &post_saved_form) + PostSaved::unsave(context.pool(), &post_saved_form) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_save_post"))?; } let post_id = data.post_id; let person_id = local_user_view.person.id; - let post_view = PostView::read(context.conn().await?, post_id, Some(person_id), None).await?; + let post_view = PostView::read(context.pool(), post_id, Some(person_id), None).await?; // Mark the post as read - mark_post_as_read(person_id, post_id, context.conn().await?).await?; + mark_post_as_read(person_id, post_id, context.pool()).await?; Ok(PostResponse { post_view }) } diff --git a/crates/api/src/post_report/create.rs b/crates/api/src/post_report/create.rs index b3ec72a38..52bc3ce75 100644 --- a/crates/api/src/post_report/create.rs +++ b/crates/api/src/post_report/create.rs @@ -24,16 +24,16 @@ impl Perform for CreatePostReport { async fn perform(&self, context: &Data) -> Result { let data: &CreatePostReport = self; let local_user_view = local_user_view_from_jwt(&data.auth, context).await?; - let local_site = LocalSite::read(context.conn().await?).await?; + let local_site = LocalSite::read(context.pool()).await?; let reason = self.reason.trim(); check_report_reason(reason, &local_site)?; let person_id = local_user_view.person.id; let post_id = data.post_id; - let post_view = PostView::read(context.conn().await?, post_id, None, None).await?; + let post_view = PostView::read(context.pool(), post_id, None, None).await?; - check_community_ban(person_id, post_view.community.id, context.conn().await?).await?; + check_community_ban(person_id, post_view.community.id, context.pool()).await?; let report_form = PostReportForm { creator_id: person_id, @@ -44,19 +44,18 @@ impl Perform for CreatePostReport { reason: reason.to_owned(), }; - let report = PostReport::report(context.conn().await?, &report_form) + let report = PostReport::report(context.pool(), &report_form) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_create_report"))?; - let post_report_view = - PostReportView::read(context.conn().await?, report.id, person_id).await?; + let post_report_view = PostReportView::read(context.pool(), report.id, person_id).await?; // Email the admins if local_site.reports_email_admins { send_new_report_email_to_admins( &post_report_view.creator.name, &post_report_view.post_creator.name, - context.conn().await?, + context.pool(), context.settings(), ) .await?; diff --git a/crates/api/src/post_report/list.rs b/crates/api/src/post_report/list.rs index 69d5fbdff..d8473f736 100644 --- a/crates/api/src/post_report/list.rs +++ b/crates/api/src/post_report/list.rs @@ -30,7 +30,7 @@ impl Perform for ListPostReports { let page = data.page; let limit = data.limit; let post_reports = PostReportQuery::builder() - .conn(context.conn().await?) + .pool(context.pool()) .my_person_id(person_id) .admin(admin) .community_id(community_id) diff --git a/crates/api/src/post_report/resolve.rs b/crates/api/src/post_report/resolve.rs index 4e148deb9..cc6d0510f 100644 --- a/crates/api/src/post_report/resolve.rs +++ b/crates/api/src/post_report/resolve.rs @@ -21,23 +21,22 @@ impl Perform for ResolvePostReport { let report_id = data.report_id; let person_id = local_user_view.person.id; - let report = PostReportView::read(context.conn().await?, report_id, person_id).await?; + let report = PostReportView::read(context.pool(), report_id, person_id).await?; let person_id = local_user_view.person.id; - is_mod_or_admin(context.conn().await?, person_id, report.community.id).await?; + is_mod_or_admin(context.pool(), person_id, report.community.id).await?; if data.resolved { - PostReport::resolve(context.conn().await?, report_id, person_id) + PostReport::resolve(context.pool(), report_id, person_id) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_resolve_report"))?; } else { - PostReport::unresolve(context.conn().await?, report_id, person_id) + PostReport::unresolve(context.pool(), report_id, person_id) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_resolve_report"))?; } - let post_report_view = - PostReportView::read(context.conn().await?, report_id, person_id).await?; + let post_report_view = PostReportView::read(context.pool(), report_id, person_id).await?; Ok(PostReportResponse { post_report_view }) } diff --git a/crates/api/src/private_message/mark_read.rs b/crates/api/src/private_message/mark_read.rs index 1cc268c47..ca3431742 100644 --- a/crates/api/src/private_message/mark_read.rs +++ b/crates/api/src/private_message/mark_read.rs @@ -26,8 +26,7 @@ impl Perform for MarkPrivateMessageAsRead { // Checking permissions let private_message_id = data.private_message_id; - let orig_private_message = - PrivateMessage::read(context.conn().await?, private_message_id).await?; + let orig_private_message = PrivateMessage::read(context.pool(), private_message_id).await?; if local_user_view.person.id != orig_private_message.recipient_id { return Err(LemmyError::from_message("couldnt_update_private_message")); } @@ -36,14 +35,14 @@ impl Perform for MarkPrivateMessageAsRead { let private_message_id = data.private_message_id; let read = data.read; PrivateMessage::update( - context.conn().await?, + context.pool(), private_message_id, &PrivateMessageUpdateForm::builder().read(Some(read)).build(), ) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_private_message"))?; - let view = PrivateMessageView::read(context.conn().await?, private_message_id).await?; + let view = PrivateMessageView::read(context.pool(), private_message_id).await?; Ok(PrivateMessageResponse { private_message_view: view, }) diff --git a/crates/api/src/private_message_report/create.rs b/crates/api/src/private_message_report/create.rs index 50dfd928b..2a2feef34 100644 --- a/crates/api/src/private_message_report/create.rs +++ b/crates/api/src/private_message_report/create.rs @@ -23,14 +23,14 @@ impl Perform for CreatePrivateMessageReport { #[tracing::instrument(skip(context))] async fn perform(&self, context: &Data) -> Result { let local_user_view = local_user_view_from_jwt(&self.auth, context).await?; - let local_site = LocalSite::read(context.conn().await?).await?; + let local_site = LocalSite::read(context.pool()).await?; let reason = self.reason.trim(); check_report_reason(reason, &local_site)?; let person_id = local_user_view.person.id; let private_message_id = self.private_message_id; - let private_message = PrivateMessage::read(context.conn().await?, private_message_id).await?; + let private_message = PrivateMessage::read(context.pool(), private_message_id).await?; let report_form = PrivateMessageReportForm { creator_id: person_id, @@ -39,19 +39,19 @@ impl Perform for CreatePrivateMessageReport { reason: reason.to_owned(), }; - let report = PrivateMessageReport::report(context.conn().await?, &report_form) + let report = PrivateMessageReport::report(context.pool(), &report_form) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_create_report"))?; let private_message_report_view = - PrivateMessageReportView::read(context.conn().await?, report.id).await?; + PrivateMessageReportView::read(context.pool(), report.id).await?; // Email the admins if local_site.reports_email_admins { send_new_report_email_to_admins( &private_message_report_view.creator.name, &private_message_report_view.private_message_creator.name, - context.conn().await?, + context.pool(), context.settings(), ) .await?; diff --git a/crates/api/src/private_message_report/list.rs b/crates/api/src/private_message_report/list.rs index 8137cf2d5..62c07325c 100644 --- a/crates/api/src/private_message_report/list.rs +++ b/crates/api/src/private_message_report/list.rs @@ -22,7 +22,7 @@ impl Perform for ListPrivateMessageReports { let page = self.page; let limit = self.limit; let private_message_reports = PrivateMessageReportQuery::builder() - .conn(context.conn().await?) + .pool(context.pool()) .unresolved_only(unresolved_only) .page(page) .limit(limit) diff --git a/crates/api/src/private_message_report/resolve.rs b/crates/api/src/private_message_report/resolve.rs index ee9b51ec0..e4fcfc856 100644 --- a/crates/api/src/private_message_report/resolve.rs +++ b/crates/api/src/private_message_report/resolve.rs @@ -22,17 +22,17 @@ impl Perform for ResolvePrivateMessageReport { let report_id = self.report_id; let person_id = local_user_view.person.id; if self.resolved { - PrivateMessageReport::resolve(context.conn().await?, report_id, person_id) + PrivateMessageReport::resolve(context.pool(), report_id, person_id) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_resolve_report"))?; } else { - PrivateMessageReport::unresolve(context.conn().await?, report_id, person_id) + PrivateMessageReport::unresolve(context.pool(), report_id, person_id) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_resolve_report"))?; } let private_message_report_view = - PrivateMessageReportView::read(context.conn().await?, report_id).await?; + PrivateMessageReportView::read(context.pool(), report_id).await?; Ok(PrivateMessageReportResponse { private_message_report_view, diff --git a/crates/api/src/site/federated_instances.rs b/crates/api/src/site/federated_instances.rs index 9eee65d5e..0d2b83bc0 100644 --- a/crates/api/src/site/federated_instances.rs +++ b/crates/api/src/site/federated_instances.rs @@ -14,7 +14,7 @@ impl Perform for GetFederatedInstances { #[tracing::instrument(skip(context))] async fn perform(&self, context: &Data) -> Result { - let site_view = SiteView::read_local(context.conn().await?).await?; + let site_view = SiteView::read_local(context.pool()).await?; let federated_instances = build_federated_instances(&site_view.local_site, context.pool()).await?; diff --git a/crates/api/src/site/leave_admin.rs b/crates/api/src/site/leave_admin.rs index d145bfec9..d7c0cf3aa 100644 --- a/crates/api/src/site/leave_admin.rs +++ b/crates/api/src/site/leave_admin.rs @@ -31,14 +31,14 @@ impl Perform for LeaveAdmin { is_admin(&local_user_view)?; // Make sure there isn't just one admin (so if one leaves, there will still be one left) - let admins = PersonView::admins(context.conn().await?).await?; + let admins = PersonView::admins(context.pool()).await?; if admins.len() == 1 { return Err(LemmyError::from_message("cannot_leave_admin")); } let person_id = local_user_view.person.id; Person::update( - context.conn().await?, + context.pool(), person_id, &PersonUpdateForm::builder().admin(Some(false)).build(), ) @@ -51,17 +51,16 @@ impl Perform for LeaveAdmin { removed: Some(true), }; - ModAdd::create(context.conn().await?, &form).await?; + ModAdd::create(context.pool(), &form).await?; // Reread site and admins - let site_view = SiteView::read_local(context.conn().await?).await?; - let admins = PersonView::admins(context.conn().await?).await?; + let site_view = SiteView::read_local(context.pool()).await?; + let admins = PersonView::admins(context.pool()).await?; - let all_languages = Language::read_all(context.conn().await?).await?; - let discussion_languages = SiteLanguage::read_local_raw(context.conn().await?).await?; - let taglines = Tagline::get_all(context.conn().await?, site_view.local_site.id).await?; - let custom_emojis = - CustomEmojiView::get_all(context.conn().await?, site_view.local_site.id).await?; + let all_languages = Language::read_all(context.pool()).await?; + let discussion_languages = SiteLanguage::read_local_raw(context.pool()).await?; + let taglines = Tagline::get_all(context.pool(), site_view.local_site.id).await?; + let custom_emojis = CustomEmojiView::get_all(context.pool(), site_view.local_site.id).await?; Ok(GetSiteResponse { site_view, diff --git a/crates/api/src/site/mod_log.rs b/crates/api/src/site/mod_log.rs index 192ef09fe..2ca725150 100644 --- a/crates/api/src/site/mod_log.rs +++ b/crates/api/src/site/mod_log.rs @@ -40,7 +40,7 @@ impl Perform for GetModlog { let data: &GetModlog = self; let local_user_view = local_user_view_from_jwt_opt(data.auth.as_ref(), context).await; - let local_site = LocalSite::read(context.conn().await?).await?; + let local_site = LocalSite::read(context.pool()).await?; check_private_instance(&local_user_view, &local_site)?; @@ -56,7 +56,7 @@ impl Perform for GetModlog { None => CommunityId(-1), }; let is_mod_of_community = data.community_id.is_some() - && is_mod_or_admin(context.conn().await?, local_person_id, community_id_value) + && is_mod_or_admin(context.pool(), local_person_id, community_id_value) .await .is_ok(); let hide_modlog_names = local_site.hide_modlog_mod_names && !is_mod_of_community && !is_admin; @@ -76,47 +76,43 @@ impl Perform for GetModlog { hide_modlog_names, }; let removed_posts = match type_ { - All | ModRemovePost => ModRemovePostView::list(context.conn().await?, params).await?, + All | ModRemovePost => ModRemovePostView::list(context.pool(), params).await?, _ => Default::default(), }; let locked_posts = match type_ { - All | ModLockPost => ModLockPostView::list(context.conn().await?, params).await?, + All | ModLockPost => ModLockPostView::list(context.pool(), params).await?, _ => Default::default(), }; let featured_posts = match type_ { - All | ModFeaturePost => ModFeaturePostView::list(context.conn().await?, params).await?, + All | ModFeaturePost => ModFeaturePostView::list(context.pool(), params).await?, _ => Default::default(), }; let removed_comments = match type_ { - All | ModRemoveComment => ModRemoveCommentView::list(context.conn().await?, params).await?, + All | ModRemoveComment => ModRemoveCommentView::list(context.pool(), params).await?, _ => Default::default(), }; let banned_from_community = match type_ { - All | ModBanFromCommunity => { - ModBanFromCommunityView::list(context.conn().await?, params).await? - } + All | ModBanFromCommunity => ModBanFromCommunityView::list(context.pool(), params).await?, _ => Default::default(), }; let added_to_community = match type_ { - All | ModAddCommunity => ModAddCommunityView::list(context.conn().await?, params).await?, + All | ModAddCommunity => ModAddCommunityView::list(context.pool(), params).await?, _ => Default::default(), }; let transferred_to_community = match type_ { - All | ModTransferCommunity => { - ModTransferCommunityView::list(context.conn().await?, params).await? - } + All | ModTransferCommunity => ModTransferCommunityView::list(context.pool(), params).await?, _ => Default::default(), }; let hidden_communities = match type_ { All | ModHideCommunity if other_person_id.is_none() => { - ModHideCommunityView::list(context.conn().await?, params).await? + ModHideCommunityView::list(context.pool(), params).await? } _ => Default::default(), }; @@ -133,40 +129,40 @@ impl Perform for GetModlog { ) = if data.community_id.is_none() { ( match type_ { - All | ModBan => ModBanView::list(context.conn().await?, params).await?, + All | ModBan => ModBanView::list(context.pool(), params).await?, _ => Default::default(), }, match type_ { - All | ModAdd => ModAddView::list(context.conn().await?, params).await?, + All | ModAdd => ModAddView::list(context.pool(), params).await?, _ => Default::default(), }, match type_ { All | ModRemoveCommunity if other_person_id.is_none() => { - ModRemoveCommunityView::list(context.conn().await?, params).await? + ModRemoveCommunityView::list(context.pool(), params).await? } _ => Default::default(), }, match type_ { All | AdminPurgePerson if other_person_id.is_none() => { - AdminPurgePersonView::list(context.conn().await?, params).await? + AdminPurgePersonView::list(context.pool(), params).await? } _ => Default::default(), }, match type_ { All | AdminPurgeCommunity if other_person_id.is_none() => { - AdminPurgeCommunityView::list(context.conn().await?, params).await? + AdminPurgeCommunityView::list(context.pool(), params).await? } _ => Default::default(), }, match type_ { All | AdminPurgePost if other_person_id.is_none() => { - AdminPurgePostView::list(context.conn().await?, params).await? + AdminPurgePostView::list(context.pool(), params).await? } _ => Default::default(), }, match type_ { All | AdminPurgeComment if other_person_id.is_none() => { - AdminPurgeCommentView::list(context.conn().await?, params).await? + AdminPurgeCommentView::list(context.pool(), params).await? } _ => Default::default(), }, diff --git a/crates/api/src/site/purge/comment.rs b/crates/api/src/site/purge/comment.rs index e8dfb0dde..7beba9c0b 100644 --- a/crates/api/src/site/purge/comment.rs +++ b/crates/api/src/site/purge/comment.rs @@ -29,13 +29,13 @@ impl Perform for PurgeComment { let comment_id = data.comment_id; // Read the comment to get the post_id - let comment = Comment::read(context.conn().await?, comment_id).await?; + let comment = Comment::read(context.pool(), comment_id).await?; let post_id = comment.post_id; // TODO read comments for pictrs images and purge them - Comment::delete(context.conn().await?, comment_id).await?; + Comment::delete(context.pool(), comment_id).await?; // Mod tables let reason = data.reason.clone(); @@ -45,7 +45,7 @@ impl Perform for PurgeComment { post_id, }; - AdminPurgeComment::create(context.conn().await?, &form).await?; + AdminPurgeComment::create(context.pool(), &form).await?; Ok(PurgeItemResponse { success: true }) } diff --git a/crates/api/src/site/purge/community.rs b/crates/api/src/site/purge/community.rs index a14a8d7d6..50482b73a 100644 --- a/crates/api/src/site/purge/community.rs +++ b/crates/api/src/site/purge/community.rs @@ -30,7 +30,7 @@ impl Perform for PurgeCommunity { let community_id = data.community_id; // Read the community to get its images - let community = Community::read(context.conn().await?, community_id).await?; + let community = Community::read(context.pool(), community_id).await?; if let Some(banner) = community.banner { purge_image_from_pictrs(context.client(), context.settings(), &banner) @@ -52,7 +52,7 @@ impl Perform for PurgeCommunity { ) .await?; - Community::delete(context.conn().await?, community_id).await?; + Community::delete(context.pool(), community_id).await?; // Mod tables let reason = data.reason.clone(); @@ -61,7 +61,7 @@ impl Perform for PurgeCommunity { reason, }; - AdminPurgeCommunity::create(context.conn().await?, &form).await?; + AdminPurgeCommunity::create(context.pool(), &form).await?; Ok(PurgeItemResponse { success: true }) } diff --git a/crates/api/src/site/purge/person.rs b/crates/api/src/site/purge/person.rs index a95a5832a..f0cbc7e8d 100644 --- a/crates/api/src/site/purge/person.rs +++ b/crates/api/src/site/purge/person.rs @@ -29,7 +29,7 @@ impl Perform for PurgePerson { // Read the person to get their images let person_id = data.person_id; - let person = Person::read(context.conn().await?, person_id).await?; + let person = Person::read(context.pool(), person_id).await?; if let Some(banner) = person.banner { purge_image_from_pictrs(context.client(), context.settings(), &banner) @@ -51,7 +51,7 @@ impl Perform for PurgePerson { ) .await?; - Person::delete(context.conn().await?, person_id).await?; + Person::delete(context.pool(), person_id).await?; // Mod tables let reason = data.reason.clone(); @@ -60,7 +60,7 @@ impl Perform for PurgePerson { reason, }; - AdminPurgePerson::create(context.conn().await?, &form).await?; + AdminPurgePerson::create(context.pool(), &form).await?; Ok(PurgeItemResponse { success: true }) } diff --git a/crates/api/src/site/purge/post.rs b/crates/api/src/site/purge/post.rs index 7b9bba859..65d390f8e 100644 --- a/crates/api/src/site/purge/post.rs +++ b/crates/api/src/site/purge/post.rs @@ -30,7 +30,7 @@ impl Perform for PurgePost { let post_id = data.post_id; // Read the post to get the community_id - let post = Post::read(context.conn().await?, post_id).await?; + let post = Post::read(context.pool(), post_id).await?; // Purge image if let Some(url) = post.url { @@ -47,7 +47,7 @@ impl Perform for PurgePost { let community_id = post.community_id; - Post::delete(context.conn().await?, post_id).await?; + Post::delete(context.pool(), post_id).await?; // Mod tables let reason = data.reason.clone(); @@ -57,7 +57,7 @@ impl Perform for PurgePost { community_id, }; - AdminPurgePost::create(context.conn().await?, &form).await?; + AdminPurgePost::create(context.pool(), &form).await?; Ok(PurgeItemResponse { success: true }) } diff --git a/crates/api/src/site/registration_applications/approve.rs b/crates/api/src/site/registration_applications/approve.rs index e13efeee6..b7f672e61 100644 --- a/crates/api/src/site/registration_applications/approve.rs +++ b/crates/api/src/site/registration_applications/approve.rs @@ -37,7 +37,7 @@ impl Perform for ApproveRegistrationApplication { }; let registration_application = - RegistrationApplication::update(context.conn().await?, app_id, &app_form).await?; + RegistrationApplication::update(context.pool(), app_id, &app_form).await?; // Update the local_user row let local_user_form = LocalUserUpdateForm::builder() @@ -45,11 +45,10 @@ impl Perform for ApproveRegistrationApplication { .build(); let approved_user_id = registration_application.local_user_id; - LocalUser::update(context.conn().await?, approved_user_id, &local_user_form).await?; + LocalUser::update(context.pool(), approved_user_id, &local_user_form).await?; if data.approve { - let approved_local_user_view = - LocalUserView::read(context.conn().await?, approved_user_id).await?; + let approved_local_user_view = LocalUserView::read(context.pool(), approved_user_id).await?; if approved_local_user_view.local_user.email.is_some() { send_application_approved_email(&approved_local_user_view, context.settings())?; @@ -58,7 +57,7 @@ impl Perform for ApproveRegistrationApplication { // Read the view let registration_application = - RegistrationApplicationView::read(context.conn().await?, app_id).await?; + RegistrationApplicationView::read(context.pool(), app_id).await?; Ok(Self::Response { registration_application, diff --git a/crates/api/src/site/registration_applications/list.rs b/crates/api/src/site/registration_applications/list.rs index 80ceea1b5..6a3599577 100644 --- a/crates/api/src/site/registration_applications/list.rs +++ b/crates/api/src/site/registration_applications/list.rs @@ -17,7 +17,7 @@ impl Perform for ListRegistrationApplications { async fn perform(&self, context: &Data) -> Result { let data = self; let local_user_view = local_user_view_from_jwt(&data.auth, context).await?; - let local_site = LocalSite::read(context.conn().await?).await?; + let local_site = LocalSite::read(context.pool()).await?; // Make sure user is an admin is_admin(&local_user_view)?; @@ -28,7 +28,7 @@ impl Perform for ListRegistrationApplications { let page = data.page; let limit = data.limit; let registration_applications = RegistrationApplicationQuery::builder() - .conn(context.conn().await?) + .pool(context.pool()) .unread_only(unread_only) .verified_email_only(Some(verified_email_only)) .page(page) diff --git a/crates/api/src/site/registration_applications/unread_count.rs b/crates/api/src/site/registration_applications/unread_count.rs index 666104635..aed07c708 100644 --- a/crates/api/src/site/registration_applications/unread_count.rs +++ b/crates/api/src/site/registration_applications/unread_count.rs @@ -16,7 +16,7 @@ impl Perform for GetUnreadRegistrationApplicationCount { async fn perform(&self, context: &Data) -> Result { let data = self; let local_user_view = local_user_view_from_jwt(&data.auth, context).await?; - let local_site = LocalSite::read(context.conn().await?).await?; + let local_site = LocalSite::read(context.pool()).await?; // Only let admins do this is_admin(&local_user_view)?; @@ -24,8 +24,7 @@ impl Perform for GetUnreadRegistrationApplicationCount { let verified_email_only = local_site.require_email_verification; let registration_applications = - RegistrationApplicationView::get_unread_count(context.conn().await?, verified_email_only) - .await?; + RegistrationApplicationView::get_unread_count(context.pool(), verified_email_only).await?; Ok(Self::Response { registration_applications, diff --git a/crates/api_common/src/build_response.rs b/crates/api_common/src/build_response.rs index 4fd9e6a93..328827b2c 100644 --- a/crates/api_common/src/build_response.rs +++ b/crates/api_common/src/build_response.rs @@ -30,7 +30,7 @@ pub async fn build_comment_response( recipient_ids: Vec, ) -> Result { let person_id = local_user_view.map(|l| l.person.id); - let comment_view = CommentView::read(context.conn().await?, comment_id, person_id).await?; + let comment_view = CommentView::read(context.pool(), comment_id, person_id).await?; Ok(CommentResponse { comment_view, recipient_ids, @@ -43,22 +43,18 @@ pub async fn build_community_response( local_user_view: LocalUserView, community_id: CommunityId, ) -> Result { - let is_mod_or_admin = is_mod_or_admin( - context.conn().await?, - local_user_view.person.id, - community_id, - ) - .await - .is_ok(); + let is_mod_or_admin = is_mod_or_admin(context.pool(), local_user_view.person.id, community_id) + .await + .is_ok(); let person_id = local_user_view.person.id; let community_view = CommunityView::read( - context.conn().await?, + context.pool(), community_id, Some(person_id), Some(is_mod_or_admin), ) .await?; - let discussion_languages = CommunityLanguage::read(context.conn().await?, community_id).await?; + let discussion_languages = CommunityLanguage::read(context.pool(), community_id).await?; Ok(CommunityResponse { community_view, @@ -72,11 +68,11 @@ pub async fn build_post_response( person_id: PersonId, post_id: PostId, ) -> Result { - let is_mod_or_admin = is_mod_or_admin(context.conn().await?, person_id, community_id) + let is_mod_or_admin = is_mod_or_admin(context.pool(), person_id, community_id) .await .is_ok(); let post_view = PostView::read( - context.conn().await?, + context.pool(), post_id, Some(person_id), Some(is_mod_or_admin), @@ -104,7 +100,7 @@ pub async fn send_local_notifs( .filter(|m| m.is_local(&context.settings().hostname) && m.name.ne(&person.name)) { let mention_name = mention.name.clone(); - let user_view = LocalUserView::read_from_name(context.conn().await?, &mention_name).await; + let user_view = LocalUserView::read_from_name(context.pool(), &mention_name).await; if let Ok(mention_user_view) = user_view { // TODO // At some point, make it so you can't tag the parent creator either @@ -119,7 +115,7 @@ pub async fn send_local_notifs( // Allow this to fail softly, since comment edits might re-update or replace it // Let the uniqueness handle this fail - PersonMention::create(context.conn().await?, &user_mention_form) + PersonMention::create(context.pool(), &user_mention_form) .await .ok(); @@ -138,19 +134,19 @@ pub async fn send_local_notifs( // Send comment_reply to the parent commenter / poster if let Some(parent_comment_id) = comment.parent_comment_id() { - let parent_comment = Comment::read(context.conn().await?, parent_comment_id).await?; + let parent_comment = Comment::read(context.pool(), parent_comment_id).await?; // Get the parent commenter local_user let parent_creator_id = parent_comment.creator_id; // Only add to recipients if that person isn't blocked - let creator_blocked = check_person_block(person.id, parent_creator_id, context.conn().await?) + let creator_blocked = check_person_block(person.id, parent_creator_id, context.pool()) .await .is_err(); // Don't send a notif to yourself if parent_comment.creator_id != person.id && !creator_blocked { - let user_view = LocalUserView::read_person(context.conn().await?, parent_creator_id).await; + let user_view = LocalUserView::read_person(context.pool(), parent_creator_id).await; if let Ok(parent_user_view) = user_view { recipient_ids.push(parent_user_view.local_user.id); @@ -162,7 +158,7 @@ pub async fn send_local_notifs( // Allow this to fail softly, since comment edits might re-update or replace it // Let the uniqueness handle this fail - CommentReply::create(context.conn().await?, &comment_reply_form) + CommentReply::create(context.pool(), &comment_reply_form) .await .ok(); @@ -180,13 +176,13 @@ pub async fn send_local_notifs( } else { // If there's no parent, its the post creator // Only add to recipients if that person isn't blocked - let creator_blocked = check_person_block(person.id, post.creator_id, context.conn().await?) + let creator_blocked = check_person_block(person.id, post.creator_id, context.pool()) .await .is_err(); if post.creator_id != person.id && !creator_blocked { let creator_id = post.creator_id; - let parent_user = LocalUserView::read_person(context.conn().await?, creator_id).await; + let parent_user = LocalUserView::read_person(context.pool(), creator_id).await; if let Ok(parent_user_view) = parent_user { recipient_ids.push(parent_user_view.local_user.id); @@ -198,7 +194,7 @@ pub async fn send_local_notifs( // Allow this to fail softly, since comment edits might re-update or replace it // Let the uniqueness handle this fail - CommentReply::create(context.conn().await?, &comment_reply_form) + CommentReply::create(context.pool(), &comment_reply_form) .await .ok(); diff --git a/crates/api_common/src/context.rs b/crates/api_common/src/context.rs index 3179bec18..42fa74964 100644 --- a/crates/api_common/src/context.rs +++ b/crates/api_common/src/context.rs @@ -1,9 +1,5 @@ -use lemmy_db_schema::{ - source::secret::Secret, - utils::{get_conn, DbPool, DbPooledConn}, -}; +use lemmy_db_schema::{source::secret::Secret, utils::DbPool}; use lemmy_utils::{ - error::LemmyResult, rate_limit::RateLimitCell, settings::{structs::Settings, SETTINGS}, }; @@ -35,9 +31,6 @@ impl LemmyContext { pub fn pool(&self) -> &DbPool { &self.pool } - pub async fn conn(&self) -> LemmyResult { - Ok(get_conn(self.pool()).await?) - } pub fn client(&self) -> &ClientWithMiddleware { &self.client } diff --git a/crates/api_common/src/utils.rs b/crates/api_common/src/utils.rs index 3fd07235d..fd143ed90 100644 --- a/crates/api_common/src/utils.rs +++ b/crates/api_common/src/utils.rs @@ -24,7 +24,7 @@ use lemmy_db_schema::{ registration_application::RegistrationApplication, }, traits::{Crud, Readable}, - utils::{get_conn, DbPool, GetConn}, + utils::DbPool, RegistrationMode, }; use lemmy_db_views::{comment_view::CommentQuery, structs::LocalUserView}; @@ -50,11 +50,11 @@ use url::{ParseError, Url}; #[tracing::instrument(skip_all)] pub async fn is_mod_or_admin( - conn: impl GetConn, + pool: &DbPool, person_id: PersonId, community_id: CommunityId, ) -> Result<(), LemmyError> { - let is_mod_or_admin = CommunityView::is_mod_or_admin(conn, person_id, community_id).await?; + let is_mod_or_admin = CommunityView::is_mod_or_admin(pool, person_id, community_id).await?; if !is_mod_or_admin { return Err(LemmyError::from_message("not_a_mod_or_admin")); } @@ -63,13 +63,13 @@ pub async fn is_mod_or_admin( #[tracing::instrument(skip_all)] pub async fn is_mod_or_admin_opt( - conn: impl GetConn, + pool: &DbPool, local_user_view: Option<&LocalUserView>, community_id: Option, ) -> Result<(), LemmyError> { if let Some(local_user_view) = local_user_view { if let Some(community_id) = community_id { - is_mod_or_admin(conn, local_user_view.person.id, community_id).await + is_mod_or_admin(pool, local_user_view.person.id, community_id).await } else { is_admin(local_user_view) } @@ -101,8 +101,8 @@ pub fn is_top_mod( } #[tracing::instrument(skip_all)] -pub async fn get_post(post_id: PostId, conn: impl GetConn) -> Result { - Post::read(conn, post_id) +pub async fn get_post(post_id: PostId, pool: &DbPool) -> Result { + Post::read(pool, post_id) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_post")) } @@ -111,11 +111,11 @@ pub async fn get_post(post_id: PostId, conn: impl GetConn) -> Result Result { let post_read_form = PostReadForm { post_id, person_id }; - PostRead::mark_as_read(conn, &post_read_form) + PostRead::mark_as_read(pool, &post_read_form) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_mark_post_as_read")) } @@ -124,11 +124,11 @@ pub async fn mark_post_as_read( pub async fn mark_post_as_unread( person_id: PersonId, post_id: PostId, - conn: impl GetConn, + pool: &DbPool, ) -> Result { let post_read_form = PostReadForm { post_id, person_id }; - PostRead::mark_as_unread(conn, &post_read_form) + PostRead::mark_as_unread(pool, &post_read_form) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_mark_post_as_read")) } @@ -142,7 +142,7 @@ pub async fn local_user_view_from_jwt( .map_err(|e| e.with_message("not_logged_in"))? .claims; let local_user_id = LocalUserId(claims.sub); - let local_user_view = LocalUserView::read(context.conn().await?, local_user_id).await?; + let local_user_view = LocalUserView::read(context.pool(), local_user_id).await?; check_user_valid( local_user_view.person.banned, local_user_view.person.ban_expires, @@ -197,9 +197,9 @@ pub fn check_user_valid( pub async fn check_community_ban( person_id: PersonId, community_id: CommunityId, - conn: impl GetConn, + pool: &DbPool, ) -> Result<(), LemmyError> { - let is_banned = CommunityPersonBanView::get(conn, person_id, community_id) + let is_banned = CommunityPersonBanView::get(pool, person_id, community_id) .await .is_ok(); if is_banned { @@ -212,9 +212,9 @@ pub async fn check_community_ban( #[tracing::instrument(skip_all)] pub async fn check_community_deleted_or_removed( community_id: CommunityId, - conn: impl GetConn, + pool: &DbPool, ) -> Result<(), LemmyError> { - let community = Community::read(conn, community_id) + let community = Community::read(pool, community_id) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?; if community.deleted || community.removed { @@ -236,9 +236,9 @@ pub fn check_post_deleted_or_removed(post: &Post) -> Result<(), LemmyError> { pub async fn check_person_block( my_id: PersonId, potential_blocker_id: PersonId, - conn: impl GetConn, + pool: &DbPool, ) -> Result<(), LemmyError> { - let is_blocked = PersonBlock::read(conn, potential_blocker_id, my_id) + let is_blocked = PersonBlock::read(pool, potential_blocker_id, my_id) .await .is_ok(); if is_blocked { @@ -272,16 +272,12 @@ pub async fn build_federated_instances( local_site: &LocalSite, pool: &DbPool, ) -> Result, LemmyError> { - let conn_0 = &mut *get_conn(pool).await?; - let conn_1 = &mut *get_conn(pool).await?; - let conn_2 = &mut *get_conn(pool).await?; - if local_site.federation_enabled { // TODO I hate that this requires 3 queries let (linked, allowed, blocked) = try_join!( - Instance::linked(conn_0), - Instance::allowlist(conn_1), - Instance::blocklist(conn_2) + Instance::linked(pool), + Instance::allowlist(pool), + Instance::blocklist(pool) )?; Ok(Some(FederatedInstances { @@ -338,7 +334,7 @@ pub fn send_email_to_user( pub async fn send_password_reset_email( user: &LocalUserView, - conn: impl GetConn, + pool: &DbPool, settings: &Settings, ) -> Result<(), LemmyError> { // Generate a random token @@ -347,7 +343,7 @@ pub async fn send_password_reset_email( // Insert the row let token2 = token.clone(); let local_user_id = user.local_user.id; - PasswordResetRequest::create_token(conn, local_user_id, &token2).await?; + PasswordResetRequest::create_token(pool, local_user_id, &token2).await?; let email = &user.local_user.email.clone().expect("email"); let lang = get_interface_language(user); @@ -362,7 +358,7 @@ pub async fn send_password_reset_email( pub async fn send_verification_email( user: &LocalUserView, new_email: &str, - conn: impl GetConn, + pool: &DbPool, settings: &Settings, ) -> Result<(), LemmyError> { let form = EmailVerificationForm { @@ -375,7 +371,7 @@ pub async fn send_verification_email( settings.get_protocol_and_hostname(), &form.verification_token ); - EmailVerification::create(conn, &form).await?; + EmailVerification::create(pool, &form).await?; let lang = get_interface_language(user); let subject = lang.verify_email_subject(&settings.hostname); @@ -453,11 +449,11 @@ pub fn send_application_approved_email( /// Send a new applicant email notification to all admins pub async fn send_new_applicant_email_to_admins( applicant_username: &str, - conn: impl GetConn, + pool: &DbPool, settings: &Settings, ) -> Result<(), LemmyError> { // Collect the admins with emails - let admins = LocalUserView::list_admins_with_emails(conn).await?; + let admins = LocalUserView::list_admins_with_emails(pool).await?; let applications_link = &format!( "{}/registration_applications", @@ -478,11 +474,11 @@ pub async fn send_new_applicant_email_to_admins( pub async fn send_new_report_email_to_admins( reporter_username: &str, reported_username: &str, - conn: impl GetConn, + pool: &DbPool, settings: &Settings, ) -> Result<(), LemmyError> { // Collect the admins with emails - let admins = LocalUserView::list_admins_with_emails(conn).await?; + let admins = LocalUserView::list_admins_with_emails(pool).await?; let reports_link = &format!("{}/reports", settings.get_protocol_and_hostname(),); @@ -499,7 +495,7 @@ pub async fn send_new_report_email_to_admins( pub async fn check_registration_application( local_user_view: &LocalUserView, local_site: &LocalSite, - conn: impl GetConn, + pool: &DbPool, ) -> Result<(), LemmyError> { if (local_site.registration_mode == RegistrationMode::RequireApplication || local_site.registration_mode == RegistrationMode::Closed) @@ -508,7 +504,7 @@ pub async fn check_registration_application( { // Fetch the registration, see if its denied let local_user_id = local_user_view.local_user.id; - let registration = RegistrationApplication::find_by_local_user_id(conn, local_user_id).await?; + let registration = RegistrationApplication::find_by_local_user_id(pool, local_user_id).await?; if let Some(deny_reason) = registration.deny_reason { let lang = get_interface_language(local_user_view); let registration_denied_message = format!("{}: {}", lang.registration_denied(), &deny_reason); @@ -537,7 +533,7 @@ pub async fn purge_image_posts_for_person( settings: &Settings, client: &ClientWithMiddleware, ) -> Result<(), LemmyError> { - let posts = Post::fetch_pictrs_posts_for_creator(get_conn(pool).await?, banned_person_id).await?; + let posts = Post::fetch_pictrs_posts_for_creator(pool, banned_person_id).await?; for post in posts { if let Some(url) = post.url { purge_image_from_pictrs(client, settings, &url).await.ok(); @@ -549,11 +545,7 @@ pub async fn purge_image_posts_for_person( } } - Post::remove_pictrs_post_images_and_thumbnails_for_creator( - get_conn(pool).await?, - banned_person_id, - ) - .await?; + Post::remove_pictrs_post_images_and_thumbnails_for_creator(pool, banned_person_id).await?; Ok(()) } @@ -564,8 +556,7 @@ pub async fn purge_image_posts_for_community( settings: &Settings, client: &ClientWithMiddleware, ) -> Result<(), LemmyError> { - let posts = - Post::fetch_pictrs_posts_for_community(get_conn(pool).await?, banned_community_id).await?; + let posts = Post::fetch_pictrs_posts_for_community(pool, banned_community_id).await?; for post in posts { if let Some(url) = post.url { purge_image_from_pictrs(client, settings, &url).await.ok(); @@ -577,11 +568,7 @@ pub async fn purge_image_posts_for_community( } } - Post::remove_pictrs_post_images_and_thumbnails_for_community( - get_conn(pool).await?, - banned_community_id, - ) - .await?; + Post::remove_pictrs_post_images_and_thumbnails_for_community(pool, banned_community_id).await?; Ok(()) } @@ -593,7 +580,7 @@ pub async fn remove_user_data( client: &ClientWithMiddleware, ) -> Result<(), LemmyError> { // Purge user images - let person = Person::read(get_conn(pool).await?, banned_person_id).await?; + let person = Person::read(pool, banned_person_id).await?; if let Some(avatar) = person.avatar { purge_image_from_pictrs(client, settings, &avatar) .await @@ -607,7 +594,7 @@ pub async fn remove_user_data( // Update the fields to None Person::update( - get_conn(pool).await?, + pool, banned_person_id, &PersonUpdateForm::builder() .avatar(Some(None)) @@ -617,7 +604,7 @@ pub async fn remove_user_data( .await?; // Posts - Post::update_removed_for_creator(get_conn(pool).await?, banned_person_id, None, true).await?; + Post::update_removed_for_creator(pool, banned_person_id, None, true).await?; // Purge image posts purge_image_posts_for_person(banned_person_id, pool, settings, client).await?; @@ -625,8 +612,7 @@ pub async fn remove_user_data( // Communities // Remove all communities where they're the top mod // for now, remove the communities manually - let first_mod_communities = - CommunityModeratorView::get_community_first_mods(get_conn(pool).await?).await?; + let first_mod_communities = CommunityModeratorView::get_community_first_mods(pool).await?; // Filter to only this banned users top communities let banned_user_first_communities: Vec = first_mod_communities @@ -637,7 +623,7 @@ pub async fn remove_user_data( for first_mod_community in banned_user_first_communities { let community_id = first_mod_community.community.id; Community::update( - get_conn(pool).await?, + pool, community_id, &CommunityUpdateForm::builder().removed(Some(true)).build(), ) @@ -654,7 +640,7 @@ pub async fn remove_user_data( } // Update the fields to None Community::update( - get_conn(pool).await?, + pool, community_id, &CommunityUpdateForm::builder() .icon(Some(None)) @@ -665,7 +651,7 @@ pub async fn remove_user_data( } // Comments - Comment::update_removed_for_creator(get_conn(pool).await?, banned_person_id, true).await?; + Comment::update_removed_for_creator(pool, banned_person_id, true).await?; Ok(()) } @@ -676,18 +662,12 @@ pub async fn remove_user_data_in_community( pool: &DbPool, ) -> Result<(), LemmyError> { // Posts - Post::update_removed_for_creator( - get_conn(pool).await?, - banned_person_id, - Some(community_id), - true, - ) - .await?; + Post::update_removed_for_creator(pool, banned_person_id, Some(community_id), true).await?; // Comments // TODO Diesel doesn't allow updates with joins, so this has to be a loop let comments = CommentQuery::builder() - .conn(get_conn(pool).await?) + .pool(pool) .creator_id(Some(banned_person_id)) .community_id(Some(community_id)) .build() @@ -697,7 +677,7 @@ pub async fn remove_user_data_in_community( for comment_view in &comments { let comment_id = comment_view.comment.id; Comment::update( - get_conn(pool).await?, + pool, comment_id, &CommentUpdateForm::builder().removed(Some(true)).build(), ) @@ -714,7 +694,7 @@ pub async fn delete_user_account( client: &ClientWithMiddleware, ) -> Result<(), LemmyError> { // Delete their images - let person = Person::read(get_conn(pool).await?, person_id).await?; + let person = Person::read(pool, person_id).await?; if let Some(avatar) = person.avatar { purge_image_from_pictrs(client, settings, &avatar) .await @@ -728,12 +708,12 @@ pub async fn delete_user_account( // No need to update avatar and banner, those are handled in Person::delete_account // Comments - Comment::permadelete_for_creator(get_conn(pool).await?, person_id) + Comment::permadelete_for_creator(pool, person_id) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?; // Posts - Post::permadelete_for_creator(get_conn(pool).await?, person_id) + Post::permadelete_for_creator(pool, person_id) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_post"))?; @@ -741,9 +721,9 @@ pub async fn delete_user_account( purge_image_posts_for_person(person_id, pool, settings, client).await?; // Leave communities they mod - CommunityModerator::leave_all_communities(get_conn(pool).await?, person_id).await?; + CommunityModerator::leave_all_communities(pool, person_id).await?; - Person::delete_account(get_conn(pool).await?, person_id).await?; + Person::delete_account(pool, person_id).await?; Ok(()) } diff --git a/crates/api_crud/src/comment/create.rs b/crates/api_crud/src/comment/create.rs index c834414e4..1bcc78483 100644 --- a/crates/api_crud/src/comment/create.rs +++ b/crates/api_crud/src/comment/create.rs @@ -43,7 +43,7 @@ impl PerformCrud for CreateComment { async fn perform(&self, context: &Data) -> Result { let data: &CreateComment = self; let local_user_view = local_user_view_from_jwt(&data.auth, context).await?; - let local_site = LocalSite::read(context.conn().await?).await?; + let local_site = LocalSite::read(context.pool()).await?; let content_slurs_removed = remove_slurs( &data.content.clone(), @@ -53,16 +53,11 @@ impl PerformCrud for CreateComment { // Check for a community ban let post_id = data.post_id; - let post = get_post(post_id, context.conn().await?).await?; + let post = get_post(post_id, context.pool()).await?; let community_id = post.community_id; - check_community_ban( - local_user_view.person.id, - community_id, - context.conn().await?, - ) - .await?; - check_community_deleted_or_removed(community_id, context.conn().await?).await?; + check_community_ban(local_user_view.person.id, community_id, context.pool()).await?; + check_community_deleted_or_removed(community_id, context.pool()).await?; check_post_deleted_or_removed(&post)?; // Check if post is locked, no new comments @@ -72,7 +67,7 @@ impl PerformCrud for CreateComment { // Fetch the parent, if it exists let parent_opt = if let Some(parent_id) = data.parent_id { - Comment::read(context.conn().await?, parent_id).await.ok() + Comment::read(context.pool(), parent_id).await.ok() } else { None }; @@ -94,7 +89,7 @@ impl PerformCrud for CreateComment { let language_id = data.language_id.unwrap_or(parent_language); CommunityLanguage::is_allowed_community_language( - context.conn().await?, + context.pool(), Some(language_id), community_id, ) @@ -109,10 +104,9 @@ impl PerformCrud for CreateComment { // Create the comment let parent_path = parent_opt.clone().map(|t| t.path); - let inserted_comment = - Comment::create(context.conn().await?, &comment_form, parent_path.as_ref()) - .await - .map_err(|e| LemmyError::from_error_message(e, "couldnt_create_comment"))?; + let inserted_comment = Comment::create(context.pool(), &comment_form, parent_path.as_ref()) + .await + .map_err(|e| LemmyError::from_error_message(e, "couldnt_create_comment"))?; // Necessary to update the ap_id let inserted_comment_id = inserted_comment.id; @@ -124,7 +118,7 @@ impl PerformCrud for CreateComment { &protocol_and_hostname, )?; let updated_comment = Comment::update( - context.conn().await?, + context.pool(), inserted_comment_id, &CommentUpdateForm::builder().ap_id(Some(apub_id)).build(), ) @@ -151,17 +145,17 @@ impl PerformCrud for CreateComment { score: 1, }; - CommentLike::like(context.conn().await?, &like_form) + CommentLike::like(context.pool(), &like_form) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_like_comment"))?; // If its a reply, mark the parent as read if let Some(parent) = parent_opt { let parent_id = parent.id; - let comment_reply = CommentReply::read_by_comment(context.conn().await?, parent_id).await; + let comment_reply = CommentReply::read_by_comment(context.pool(), parent_id).await; if let Ok(reply) = comment_reply { CommentReply::update( - context.conn().await?, + context.pool(), reply.id, &CommentReplyUpdateForm { read: Some(true) }, ) @@ -172,11 +166,10 @@ impl PerformCrud for CreateComment { // If the parent has PersonMentions mark them as read too let person_id = local_user_view.person.id; let person_mention = - PersonMention::read_by_comment_and_person(context.conn().await?, parent_id, person_id) - .await; + PersonMention::read_by_comment_and_person(context.pool(), parent_id, person_id).await; if let Ok(mention) = person_mention { PersonMention::update( - context.conn().await?, + context.pool(), mention.id, &PersonMentionUpdateForm { read: Some(true) }, ) diff --git a/crates/api_crud/src/comment/delete.rs b/crates/api_crud/src/comment/delete.rs index 9a07543cb..864daded8 100644 --- a/crates/api_crud/src/comment/delete.rs +++ b/crates/api_crud/src/comment/delete.rs @@ -26,7 +26,7 @@ impl PerformCrud for DeleteComment { let local_user_view = local_user_view_from_jwt(&data.auth, context).await?; let comment_id = data.comment_id; - let orig_comment = CommentView::read(context.conn().await?, comment_id, None).await?; + let orig_comment = CommentView::read(context.pool(), comment_id, None).await?; // Dont delete it if its already been deleted. if orig_comment.comment.deleted == data.deleted { @@ -36,7 +36,7 @@ impl PerformCrud for DeleteComment { check_community_ban( local_user_view.person.id, orig_comment.community.id, - context.conn().await?, + context.pool(), ) .await?; @@ -48,7 +48,7 @@ impl PerformCrud for DeleteComment { // Do the delete let deleted = data.deleted; let updated_comment = Comment::update( - context.conn().await?, + context.pool(), comment_id, &CommentUpdateForm::builder().deleted(Some(deleted)).build(), ) @@ -56,7 +56,7 @@ impl PerformCrud for DeleteComment { .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?; let post_id = updated_comment.post_id; - let post = Post::read(context.conn().await?, post_id).await?; + let post = Post::read(context.pool(), post_id).await?; let recipient_ids = send_local_notifs( vec![], &updated_comment, diff --git a/crates/api_crud/src/comment/read.rs b/crates/api_crud/src/comment/read.rs index 573a9004e..2ae719738 100644 --- a/crates/api_crud/src/comment/read.rs +++ b/crates/api_crud/src/comment/read.rs @@ -17,7 +17,7 @@ impl PerformCrud for GetComment { async fn perform(&self, context: &Data) -> Result { let data = self; let local_user_view = local_user_view_from_jwt_opt(data.auth.as_ref(), context).await; - let local_site = LocalSite::read(context.conn().await?).await?; + let local_site = LocalSite::read(context.pool()).await?; check_private_instance(&local_user_view, &local_site)?; diff --git a/crates/api_crud/src/comment/remove.rs b/crates/api_crud/src/comment/remove.rs index 0bf879d30..6e4e55281 100644 --- a/crates/api_crud/src/comment/remove.rs +++ b/crates/api_crud/src/comment/remove.rs @@ -27,18 +27,18 @@ impl PerformCrud for RemoveComment { let local_user_view = local_user_view_from_jwt(&data.auth, context).await?; let comment_id = data.comment_id; - let orig_comment = CommentView::read(context.conn().await?, comment_id, None).await?; + let orig_comment = CommentView::read(context.pool(), comment_id, None).await?; check_community_ban( local_user_view.person.id, orig_comment.community.id, - context.conn().await?, + context.pool(), ) .await?; // Verify that only a mod or admin can remove is_mod_or_admin( - context.conn().await?, + context.pool(), local_user_view.person.id, orig_comment.community.id, ) @@ -47,7 +47,7 @@ impl PerformCrud for RemoveComment { // Do the remove let removed = data.removed; let updated_comment = Comment::update( - context.conn().await?, + context.pool(), comment_id, &CommentUpdateForm::builder().removed(Some(removed)).build(), ) @@ -61,10 +61,10 @@ impl PerformCrud for RemoveComment { removed: Some(removed), reason: data.reason.clone(), }; - ModRemoveComment::create(context.conn().await?, &form).await?; + ModRemoveComment::create(context.pool(), &form).await?; let post_id = updated_comment.post_id; - let post = Post::read(context.conn().await?, post_id).await?; + let post = Post::read(context.pool(), post_id).await?; let recipient_ids = send_local_notifs( vec![], &updated_comment, diff --git a/crates/api_crud/src/comment/update.rs b/crates/api_crud/src/comment/update.rs index 37881e6ea..3504e784d 100644 --- a/crates/api_crud/src/comment/update.rs +++ b/crates/api_crud/src/comment/update.rs @@ -33,15 +33,15 @@ impl PerformCrud for EditComment { async fn perform(&self, context: &Data) -> Result { let data: &EditComment = self; let local_user_view = local_user_view_from_jwt(&data.auth, context).await?; - let local_site = LocalSite::read(context.conn().await?).await?; + let local_site = LocalSite::read(context.pool()).await?; let comment_id = data.comment_id; - let orig_comment = CommentView::read(context.conn().await?, comment_id, None).await?; + let orig_comment = CommentView::read(context.pool(), comment_id, None).await?; check_community_ban( local_user_view.person.id, orig_comment.community.id, - context.conn().await?, + context.pool(), ) .await?; @@ -52,7 +52,7 @@ impl PerformCrud for EditComment { let language_id = self.language_id; CommunityLanguage::is_allowed_community_language( - context.conn().await?, + context.pool(), language_id, orig_comment.community.id, ) @@ -72,7 +72,7 @@ impl PerformCrud for EditComment { .language_id(data.language_id) .updated(Some(Some(naive_now()))) .build(); - let updated_comment = Comment::update(context.conn().await?, comment_id, &form) + let updated_comment = Comment::update(context.pool(), comment_id, &form) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_comment"))?; diff --git a/crates/api_crud/src/community/create.rs b/crates/api_crud/src/community/create.rs index 28a97b526..0e55beac9 100644 --- a/crates/api_crud/src/community/create.rs +++ b/crates/api_crud/src/community/create.rs @@ -48,7 +48,7 @@ impl PerformCrud for CreateCommunity { async fn perform(&self, context: &Data) -> Result { let data: &CreateCommunity = self; let local_user_view = local_user_view_from_jwt(&data.auth, context).await?; - let site_view = SiteView::read_local(context.conn().await?).await?; + let site_view = SiteView::read_local(context.pool()).await?; let local_site = site_view.local_site; if local_site.community_creation_admin_only && is_admin(&local_user_view).is_err() { @@ -75,8 +75,7 @@ impl PerformCrud for CreateCommunity { &data.name, &context.settings().get_protocol_and_hostname(), )?; - let community_dupe = - Community::read_from_apub_id(context.conn().await?, &community_actor_id).await?; + let community_dupe = Community::read_from_apub_id(context.pool(), &community_actor_id).await?; if community_dupe.is_some() { return Err(LemmyError::from_message("community_already_exists")); } @@ -101,7 +100,7 @@ impl PerformCrud for CreateCommunity { .instance_id(site_view.site.instance_id) .build(); - let inserted_community = Community::create(context.conn().await?, &community_form) + let inserted_community = Community::create(context.pool(), &community_form) .await .map_err(|e| LemmyError::from_error_message(e, "community_already_exists"))?; @@ -111,7 +110,7 @@ impl PerformCrud for CreateCommunity { person_id: local_user_view.person.id, }; - CommunityModerator::join(context.conn().await?, &community_moderator_form) + CommunityModerator::join(context.pool(), &community_moderator_form) .await .map_err(|e| LemmyError::from_error_message(e, "community_moderator_already_exists"))?; @@ -122,21 +121,21 @@ impl PerformCrud for CreateCommunity { pending: false, }; - CommunityFollower::follow(context.conn().await?, &community_follower_form) + CommunityFollower::follow(context.pool(), &community_follower_form) .await .map_err(|e| LemmyError::from_error_message(e, "community_follower_already_exists"))?; // Update the discussion_languages if that's provided let community_id = inserted_community.id; if let Some(languages) = data.discussion_languages.clone() { - let site_languages = SiteLanguage::read_local_raw(context.conn().await?).await?; + let site_languages = SiteLanguage::read_local_raw(context.pool()).await?; // check that community languages are a subset of site languages // https://stackoverflow.com/a/64227550 let is_subset = languages.iter().all(|item| site_languages.contains(item)); if !is_subset { return Err(LemmyError::from_message("language_not_allowed")); } - CommunityLanguage::update(context.conn().await?, languages, community_id).await?; + CommunityLanguage::update(context.pool(), languages, community_id).await?; } build_community_response(context, local_user_view, community_id).await diff --git a/crates/api_crud/src/community/delete.rs b/crates/api_crud/src/community/delete.rs index fd888f1a8..019e9f1da 100644 --- a/crates/api_crud/src/community/delete.rs +++ b/crates/api_crud/src/community/delete.rs @@ -25,7 +25,7 @@ impl PerformCrud for DeleteCommunity { // Fetch the community mods let community_id = data.community_id; let community_mods = - CommunityModeratorView::for_community(context.conn().await?, community_id).await?; + CommunityModeratorView::for_community(context.pool(), community_id).await?; // Make sure deleter is the top mod is_top_mod(&local_user_view, &community_mods)?; @@ -34,7 +34,7 @@ impl PerformCrud for DeleteCommunity { let community_id = data.community_id; let deleted = data.deleted; Community::update( - context.conn().await?, + context.pool(), community_id, &CommunityUpdateForm::builder() .deleted(Some(deleted)) diff --git a/crates/api_crud/src/community/list.rs b/crates/api_crud/src/community/list.rs index 10544d7f8..d37dd2dc2 100644 --- a/crates/api_crud/src/community/list.rs +++ b/crates/api_crud/src/community/list.rs @@ -20,7 +20,7 @@ impl PerformCrud for ListCommunities { ) -> Result { let data: &ListCommunities = self; let local_user_view = local_user_view_from_jwt_opt(data.auth.as_ref(), context).await; - let local_site = LocalSite::read(context.conn().await?).await?; + let local_site = LocalSite::read(context.pool()).await?; let is_admin = local_user_view.as_ref().map(|luv| is_admin(luv).is_ok()); check_private_instance(&local_user_view, &local_site)?; @@ -32,7 +32,7 @@ impl PerformCrud for ListCommunities { let limit = data.limit; let local_user = local_user_view.map(|l| l.local_user); let communities = CommunityQuery::builder() - .conn(context.conn().await?) + .pool(context.pool()) .listing_type(listing_type) .show_nsfw(show_nsfw) .sort(sort) diff --git a/crates/api_crud/src/community/remove.rs b/crates/api_crud/src/community/remove.rs index bf82dfe02..52a503c45 100644 --- a/crates/api_crud/src/community/remove.rs +++ b/crates/api_crud/src/community/remove.rs @@ -31,7 +31,7 @@ impl PerformCrud for RemoveCommunity { let community_id = data.community_id; let removed = data.removed; Community::update( - context.conn().await?, + context.pool(), community_id, &CommunityUpdateForm::builder() .removed(Some(removed)) @@ -49,7 +49,7 @@ impl PerformCrud for RemoveCommunity { reason: data.reason.clone(), expires, }; - ModRemoveCommunity::create(context.conn().await?, &form).await?; + ModRemoveCommunity::create(context.pool(), &form).await?; build_community_response(context, local_user_view, community_id).await } diff --git a/crates/api_crud/src/community/update.rs b/crates/api_crud/src/community/update.rs index 75abbaf43..dec62865f 100644 --- a/crates/api_crud/src/community/update.rs +++ b/crates/api_crud/src/community/update.rs @@ -30,7 +30,7 @@ impl PerformCrud for EditCommunity { async fn perform(&self, context: &Data) -> Result { let data: &EditCommunity = self; let local_user_view = local_user_view_from_jwt(&data.auth, context).await?; - let local_site = LocalSite::read(context.conn().await?).await?; + let local_site = LocalSite::read(context.pool()).await?; let icon = diesel_option_overwrite_to_url(&data.icon)?; let banner = diesel_option_overwrite_to_url(&data.banner)?; @@ -43,24 +43,23 @@ impl PerformCrud for EditCommunity { // Verify its a mod (only mods can edit it) let community_id = data.community_id; - let mods: Vec = - CommunityModeratorView::for_community(context.conn().await?, community_id) - .await - .map(|v| v.into_iter().map(|m| m.moderator.id).collect())?; + let mods: Vec = CommunityModeratorView::for_community(context.pool(), community_id) + .await + .map(|v| v.into_iter().map(|m| m.moderator.id).collect())?; if !mods.contains(&local_user_view.person.id) { return Err(LemmyError::from_message("not_a_moderator")); } let community_id = data.community_id; if let Some(languages) = data.discussion_languages.clone() { - let site_languages = SiteLanguage::read_local_raw(context.conn().await?).await?; + let site_languages = SiteLanguage::read_local_raw(context.pool()).await?; // check that community languages are a subset of site languages // https://stackoverflow.com/a/64227550 let is_subset = languages.iter().all(|item| site_languages.contains(item)); if !is_subset { return Err(LemmyError::from_message("language_not_allowed")); } - CommunityLanguage::update(context.conn().await?, languages, community_id).await?; + CommunityLanguage::update(context.pool(), languages, community_id).await?; } let community_form = CommunityUpdateForm::builder() @@ -74,7 +73,7 @@ impl PerformCrud for EditCommunity { .build(); let community_id = data.community_id; - Community::update(context.conn().await?, community_id, &community_form) + Community::update(context.pool(), community_id, &community_form) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_community"))?; diff --git a/crates/api_crud/src/custom_emoji/create.rs b/crates/api_crud/src/custom_emoji/create.rs index e2a71d80a..5aaf56125 100644 --- a/crates/api_crud/src/custom_emoji/create.rs +++ b/crates/api_crud/src/custom_emoji/create.rs @@ -22,7 +22,7 @@ impl PerformCrud for CreateCustomEmoji { let data: &CreateCustomEmoji = self; let local_user_view = local_user_view_from_jwt(&data.auth, context).await?; - let local_site = LocalSite::read(context.conn().await?).await?; + let local_site = LocalSite::read(context.pool()).await?; // Make sure user is an admin is_admin(&local_user_view)?; @@ -33,7 +33,7 @@ impl PerformCrud for CreateCustomEmoji { .category(data.category.to_string()) .image_url(data.clone().image_url.into()) .build(); - let emoji = CustomEmoji::create(context.conn().await?, &emoji_form).await?; + let emoji = CustomEmoji::create(context.pool(), &emoji_form).await?; let mut keywords = vec![]; for keyword in &data.keywords { let keyword_form = CustomEmojiKeywordInsertForm::builder() @@ -42,8 +42,8 @@ impl PerformCrud for CreateCustomEmoji { .build(); keywords.push(keyword_form); } - CustomEmojiKeyword::create(context.conn().await?, keywords).await?; - let view = CustomEmojiView::get(context.conn().await?, emoji.id).await?; + CustomEmojiKeyword::create(context.pool(), keywords).await?; + let view = CustomEmojiView::get(context.pool(), emoji.id).await?; Ok(CustomEmojiResponse { custom_emoji: view }) } } diff --git a/crates/api_crud/src/custom_emoji/delete.rs b/crates/api_crud/src/custom_emoji/delete.rs index 95e9d4c6b..45dc6eaee 100644 --- a/crates/api_crud/src/custom_emoji/delete.rs +++ b/crates/api_crud/src/custom_emoji/delete.rs @@ -22,7 +22,7 @@ impl PerformCrud for DeleteCustomEmoji { // Make sure user is an admin is_admin(&local_user_view)?; - CustomEmoji::delete(context.conn().await?, data.id).await?; + CustomEmoji::delete(context.pool(), data.id).await?; Ok(DeleteCustomEmojiResponse { id: data.id, success: true, diff --git a/crates/api_crud/src/custom_emoji/update.rs b/crates/api_crud/src/custom_emoji/update.rs index f3ca1b152..f56763e9d 100644 --- a/crates/api_crud/src/custom_emoji/update.rs +++ b/crates/api_crud/src/custom_emoji/update.rs @@ -22,7 +22,7 @@ impl PerformCrud for EditCustomEmoji { let data: &EditCustomEmoji = self; let local_user_view = local_user_view_from_jwt(&data.auth, context).await?; - let local_site = LocalSite::read(context.conn().await?).await?; + let local_site = LocalSite::read(context.pool()).await?; // Make sure user is an admin is_admin(&local_user_view)?; @@ -32,8 +32,8 @@ impl PerformCrud for EditCustomEmoji { .category(data.category.to_string()) .image_url(data.clone().image_url.into()) .build(); - let emoji = CustomEmoji::update(context.conn().await?, data.id, &emoji_form).await?; - CustomEmojiKeyword::delete(context.conn().await?, data.id).await?; + let emoji = CustomEmoji::update(context.pool(), data.id, &emoji_form).await?; + CustomEmojiKeyword::delete(context.pool(), data.id).await?; let mut keywords = vec![]; for keyword in &data.keywords { let keyword_form = CustomEmojiKeywordInsertForm::builder() @@ -42,8 +42,8 @@ impl PerformCrud for EditCustomEmoji { .build(); keywords.push(keyword_form); } - CustomEmojiKeyword::create(context.conn().await?, keywords).await?; - let view = CustomEmojiView::get(context.conn().await?, emoji.id).await?; + CustomEmojiKeyword::create(context.pool(), keywords).await?; + let view = CustomEmojiView::get(context.pool(), emoji.id).await?; Ok(CustomEmojiResponse { custom_emoji: view }) } } diff --git a/crates/api_crud/src/post/create.rs b/crates/api_crud/src/post/create.rs index 76e4376cf..1dcc90241 100644 --- a/crates/api_crud/src/post/create.rs +++ b/crates/api_crud/src/post/create.rs @@ -46,7 +46,7 @@ impl PerformCrud for CreatePost { async fn perform(&self, context: &Data) -> Result { let data: &CreatePost = self; let local_user_view = local_user_view_from_jwt(&data.auth, context).await?; - let local_site = LocalSite::read(context.conn().await?).await?; + let local_site = LocalSite::read(context.pool()).await?; let slur_regex = local_site_to_slur_regex(&local_site); check_slurs(&data.name, &slur_regex)?; @@ -59,20 +59,15 @@ impl PerformCrud for CreatePost { is_valid_post_title(&data.name)?; is_valid_body_field(&data.body, true)?; - check_community_ban( - local_user_view.person.id, - data.community_id, - context.conn().await?, - ) - .await?; - check_community_deleted_or_removed(data.community_id, context.conn().await?).await?; + check_community_ban(local_user_view.person.id, data.community_id, context.pool()).await?; + check_community_deleted_or_removed(data.community_id, context.pool()).await?; let community_id = data.community_id; - let community = Community::read(context.conn().await?, community_id).await?; + let community = Community::read(context.pool(), community_id).await?; if community.posting_restricted_to_mods { let community_id = data.community_id; let is_mod = CommunityView::is_mod_or_admin( - context.conn().await?, + context.pool(), local_user_view.local_user.person_id, community_id, ) @@ -92,20 +87,11 @@ impl PerformCrud for CreatePost { let language_id = match data.language_id { Some(lid) => Some(lid), None => { - default_post_language( - context.conn().await?, - community_id, - local_user_view.local_user.id, - ) - .await? + default_post_language(context.pool(), community_id, local_user_view.local_user.id).await? } }; - CommunityLanguage::is_allowed_community_language( - context.conn().await?, - language_id, - community_id, - ) - .await?; + CommunityLanguage::is_allowed_community_language(context.pool(), language_id, community_id) + .await?; let post_form = PostInsertForm::builder() .name(data.name.trim().to_owned()) @@ -121,7 +107,7 @@ impl PerformCrud for CreatePost { .thumbnail_url(thumbnail_url) .build(); - let inserted_post = Post::create(context.conn().await?, &post_form) + let inserted_post = Post::create(context.pool(), &post_form) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_create_post"))?; @@ -133,7 +119,7 @@ impl PerformCrud for CreatePost { &protocol_and_hostname, )?; let updated_post = Post::update( - context.conn().await?, + context.pool(), inserted_post_id, &PostUpdateForm::builder().ap_id(Some(apub_id)).build(), ) @@ -149,12 +135,12 @@ impl PerformCrud for CreatePost { score: 1, }; - PostLike::like(context.conn().await?, &like_form) + PostLike::like(context.pool(), &like_form) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_like_post"))?; // Mark the post as read - mark_post_as_read(person_id, post_id, context.conn().await?).await?; + mark_post_as_read(person_id, post_id, context.pool()).await?; if let Some(url) = &updated_post.url { let mut webmention = diff --git a/crates/api_crud/src/post/delete.rs b/crates/api_crud/src/post/delete.rs index 3802b39ed..6e6a4c076 100644 --- a/crates/api_crud/src/post/delete.rs +++ b/crates/api_crud/src/post/delete.rs @@ -22,7 +22,7 @@ impl PerformCrud for DeletePost { let local_user_view = local_user_view_from_jwt(&data.auth, context).await?; let post_id = data.post_id; - let orig_post = Post::read(context.conn().await?, post_id).await?; + let orig_post = Post::read(context.pool(), post_id).await?; // Dont delete it if its already been deleted. if orig_post.deleted == data.deleted { @@ -32,10 +32,10 @@ impl PerformCrud for DeletePost { check_community_ban( local_user_view.person.id, orig_post.community_id, - context.conn().await?, + context.pool(), ) .await?; - check_community_deleted_or_removed(orig_post.community_id, context.conn().await?).await?; + check_community_deleted_or_removed(orig_post.community_id, context.pool()).await?; // Verify that only the creator can delete if !Post::is_post_creator(local_user_view.person.id, orig_post.creator_id) { @@ -46,7 +46,7 @@ impl PerformCrud for DeletePost { let post_id = data.post_id; let deleted = data.deleted; Post::update( - context.conn().await?, + context.pool(), post_id, &PostUpdateForm::builder().deleted(Some(deleted)).build(), ) diff --git a/crates/api_crud/src/post/read.rs b/crates/api_crud/src/post/read.rs index 1b8b610bd..d1851f33e 100644 --- a/crates/api_crud/src/post/read.rs +++ b/crates/api_crud/src/post/read.rs @@ -27,7 +27,7 @@ impl PerformCrud for GetPost { async fn perform(&self, context: &Data) -> Result { let data: &GetPost = self; let local_user_view = local_user_view_from_jwt_opt(data.auth.as_ref(), context).await; - let local_site = LocalSite::read(context.conn().await?).await?; + let local_site = LocalSite::read(context.pool()).await?; check_private_instance(&local_user_view, &local_site)?; @@ -37,7 +37,7 @@ impl PerformCrud for GetPost { let post_id = if let Some(id) = data.id { id } else if let Some(comment_id) = data.comment_id { - Comment::read(context.conn().await?, comment_id) + Comment::read(context.pool(), comment_id) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_post"))? .post_id @@ -46,35 +46,25 @@ impl PerformCrud for GetPost { }; // Check to see if the person is a mod or admin, to show deleted / removed - let community_id = Post::read(context.conn().await?, post_id) - .await? - .community_id; - let is_mod_or_admin = is_mod_or_admin_opt( - context.conn().await?, - local_user_view.as_ref(), - Some(community_id), - ) - .await - .is_ok(); + let community_id = Post::read(context.pool(), post_id).await?.community_id; + let is_mod_or_admin = + is_mod_or_admin_opt(context.pool(), local_user_view.as_ref(), Some(community_id)) + .await + .is_ok(); - let post_view = PostView::read( - context.conn().await?, - post_id, - person_id, - Some(is_mod_or_admin), - ) - .await - .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_post"))?; + let post_view = PostView::read(context.pool(), post_id, person_id, Some(is_mod_or_admin)) + .await + .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_post"))?; // Mark the post as read let post_id = post_view.post.id; if let Some(person_id) = person_id { - mark_post_as_read(person_id, post_id, context.conn().await?).await?; + mark_post_as_read(person_id, post_id, context.pool()).await?; } // Necessary for the sidebar subscribed let community_view = CommunityView::read( - context.conn().await?, + context.pool(), community_id, person_id, Some(is_mod_or_admin), @@ -92,18 +82,17 @@ impl PerformCrud for GetPost { read_comments, ..PersonPostAggregatesForm::default() }; - PersonPostAggregates::upsert(context.conn().await?, &person_post_agg_form) + PersonPostAggregates::upsert(context.pool(), &person_post_agg_form) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_post"))?; } - let moderators = - CommunityModeratorView::for_community(context.conn().await?, community_id).await?; + let moderators = CommunityModeratorView::for_community(context.pool(), community_id).await?; // Fetch the cross_posts let cross_posts = if let Some(url) = &post_view.post.url { let mut x_posts = PostQuery::builder() - .conn(context.conn().await?) + .pool(context.pool()) .url_search(Some(url.inner().as_str().into())) .build() .list() diff --git a/crates/api_crud/src/post/remove.rs b/crates/api_crud/src/post/remove.rs index 97681154d..7f379169e 100644 --- a/crates/api_crud/src/post/remove.rs +++ b/crates/api_crud/src/post/remove.rs @@ -25,18 +25,18 @@ impl PerformCrud for RemovePost { let local_user_view = local_user_view_from_jwt(&data.auth, context).await?; let post_id = data.post_id; - let orig_post = Post::read(context.conn().await?, post_id).await?; + let orig_post = Post::read(context.pool(), post_id).await?; check_community_ban( local_user_view.person.id, orig_post.community_id, - context.conn().await?, + context.pool(), ) .await?; // Verify that only the mods can remove is_mod_or_admin( - context.conn().await?, + context.pool(), local_user_view.person.id, orig_post.community_id, ) @@ -46,7 +46,7 @@ impl PerformCrud for RemovePost { let post_id = data.post_id; let removed = data.removed; Post::update( - context.conn().await?, + context.pool(), post_id, &PostUpdateForm::builder().removed(Some(removed)).build(), ) @@ -59,7 +59,7 @@ impl PerformCrud for RemovePost { removed: Some(removed), reason: data.reason.clone(), }; - ModRemovePost::create(context.conn().await?, &form).await?; + ModRemovePost::create(context.pool(), &form).await?; build_post_response( context, diff --git a/crates/api_crud/src/post/update.rs b/crates/api_crud/src/post/update.rs index aef5bd88d..632bc5ae7 100644 --- a/crates/api_crud/src/post/update.rs +++ b/crates/api_crud/src/post/update.rs @@ -32,7 +32,7 @@ impl PerformCrud for EditPost { async fn perform(&self, context: &Data) -> Result { let data: &EditPost = self; let local_user_view = local_user_view_from_jwt(&data.auth, context).await?; - let local_site = LocalSite::read(context.conn().await?).await?; + let local_site = LocalSite::read(context.pool()).await?; let data_url = data.url.as_ref(); @@ -52,12 +52,12 @@ impl PerformCrud for EditPost { is_valid_body_field(&data.body, true)?; let post_id = data.post_id; - let orig_post = Post::read(context.conn().await?, post_id).await?; + let orig_post = Post::read(context.pool(), post_id).await?; check_community_ban( local_user_view.person.id, orig_post.community_id, - context.conn().await?, + context.pool(), ) .await?; @@ -76,7 +76,7 @@ impl PerformCrud for EditPost { let language_id = self.language_id; CommunityLanguage::is_allowed_community_language( - context.conn().await?, + context.pool(), language_id, orig_post.community_id, ) @@ -96,7 +96,7 @@ impl PerformCrud for EditPost { .build(); let post_id = data.post_id; - Post::update(context.conn().await?, post_id, &post_form) + Post::update(context.pool(), post_id, &post_form) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_create_post"))?; diff --git a/crates/api_crud/src/private_message/create.rs b/crates/api_crud/src/private_message/create.rs index f5839b03b..e1a855463 100644 --- a/crates/api_crud/src/private_message/create.rs +++ b/crates/api_crud/src/private_message/create.rs @@ -37,7 +37,7 @@ impl PerformCrud for CreatePrivateMessage { ) -> Result { let data: &CreatePrivateMessage = self; let local_user_view = local_user_view_from_jwt(&data.auth, context).await?; - let local_site = LocalSite::read(context.conn().await?).await?; + let local_site = LocalSite::read(context.pool()).await?; let content_slurs_removed = remove_slurs( &data.content.clone(), @@ -45,12 +45,7 @@ impl PerformCrud for CreatePrivateMessage { ); is_valid_body_field(&Some(content_slurs_removed.clone()), false)?; - check_person_block( - local_user_view.person.id, - data.recipient_id, - context.conn().await?, - ) - .await?; + check_person_block(local_user_view.person.id, data.recipient_id, context.pool()).await?; let private_message_form = PrivateMessageInsertForm::builder() .content(content_slurs_removed.clone()) @@ -59,7 +54,7 @@ impl PerformCrud for CreatePrivateMessage { .build(); let inserted_private_message = - match PrivateMessage::create(context.conn().await?, &private_message_form).await { + match PrivateMessage::create(context.pool(), &private_message_form).await { Ok(private_message) => private_message, Err(e) => { return Err(LemmyError::from_error_message( @@ -77,7 +72,7 @@ impl PerformCrud for CreatePrivateMessage { &protocol_and_hostname, )?; PrivateMessage::update( - context.conn().await?, + context.pool(), inserted_private_message.id, &PrivateMessageUpdateForm::builder() .ap_id(Some(apub_id)) @@ -86,12 +81,12 @@ impl PerformCrud for CreatePrivateMessage { .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_create_private_message"))?; - let view = PrivateMessageView::read(context.conn().await?, inserted_private_message.id).await?; + let view = PrivateMessageView::read(context.pool(), inserted_private_message.id).await?; // Send email to the local recipient, if one exists if view.recipient.local { let recipient_id = data.recipient_id; - let local_recipient = LocalUserView::read_person(context.conn().await?, recipient_id).await?; + let local_recipient = LocalUserView::read_person(context.pool(), recipient_id).await?; let lang = get_interface_language(&local_recipient); let inbox_link = format!("{}/inbox", context.settings().get_protocol_and_hostname()); let sender_name = &local_user_view.person.name; diff --git a/crates/api_crud/src/private_message/delete.rs b/crates/api_crud/src/private_message/delete.rs index 1990fec9c..b8e3c3b11 100644 --- a/crates/api_crud/src/private_message/delete.rs +++ b/crates/api_crud/src/private_message/delete.rs @@ -26,8 +26,7 @@ impl PerformCrud for DeletePrivateMessage { // Checking permissions let private_message_id = data.private_message_id; - let orig_private_message = - PrivateMessage::read(context.conn().await?, private_message_id).await?; + let orig_private_message = PrivateMessage::read(context.pool(), private_message_id).await?; if local_user_view.person.id != orig_private_message.creator_id { return Err(LemmyError::from_message("no_private_message_edit_allowed")); } @@ -36,7 +35,7 @@ impl PerformCrud for DeletePrivateMessage { let private_message_id = data.private_message_id; let deleted = data.deleted; PrivateMessage::update( - context.conn().await?, + context.pool(), private_message_id, &PrivateMessageUpdateForm::builder() .deleted(Some(deleted)) @@ -45,7 +44,7 @@ impl PerformCrud for DeletePrivateMessage { .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_private_message"))?; - let view = PrivateMessageView::read(context.conn().await?, private_message_id).await?; + let view = PrivateMessageView::read(context.pool(), private_message_id).await?; Ok(PrivateMessageResponse { private_message_view: view, }) diff --git a/crates/api_crud/src/private_message/read.rs b/crates/api_crud/src/private_message/read.rs index 7b58517df..679cd09f7 100644 --- a/crates/api_crud/src/private_message/read.rs +++ b/crates/api_crud/src/private_message/read.rs @@ -25,7 +25,7 @@ impl PerformCrud for GetPrivateMessages { let limit = data.limit; let unread_only = data.unread_only; let mut messages = PrivateMessageQuery::builder() - .conn(context.conn().await?) + .pool(context.pool()) .recipient_id(person_id) .page(page) .limit(limit) diff --git a/crates/api_crud/src/private_message/update.rs b/crates/api_crud/src/private_message/update.rs index e28c22ffb..b2d8e48f9 100644 --- a/crates/api_crud/src/private_message/update.rs +++ b/crates/api_crud/src/private_message/update.rs @@ -30,12 +30,11 @@ impl PerformCrud for EditPrivateMessage { ) -> Result { let data: &EditPrivateMessage = self; let local_user_view = local_user_view_from_jwt(&data.auth, context).await?; - let local_site = LocalSite::read(context.conn().await?).await?; + let local_site = LocalSite::read(context.pool()).await?; // Checking permissions let private_message_id = data.private_message_id; - let orig_private_message = - PrivateMessage::read(context.conn().await?, private_message_id).await?; + let orig_private_message = PrivateMessage::read(context.pool(), private_message_id).await?; if local_user_view.person.id != orig_private_message.creator_id { return Err(LemmyError::from_message("no_private_message_edit_allowed")); } @@ -46,7 +45,7 @@ impl PerformCrud for EditPrivateMessage { let private_message_id = data.private_message_id; PrivateMessage::update( - context.conn().await?, + context.pool(), private_message_id, &PrivateMessageUpdateForm::builder() .content(Some(content_slurs_removed)) @@ -56,7 +55,7 @@ impl PerformCrud for EditPrivateMessage { .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_update_private_message"))?; - let view = PrivateMessageView::read(context.conn().await?, private_message_id).await?; + let view = PrivateMessageView::read(context.pool(), private_message_id).await?; Ok(PrivateMessageResponse { private_message_view: view, diff --git a/crates/api_crud/src/site/create.rs b/crates/api_crud/src/site/create.rs index 8efba6752..838d5bc40 100644 --- a/crates/api_crud/src/site/create.rs +++ b/crates/api_crud/src/site/create.rs @@ -48,9 +48,8 @@ impl PerformCrud for CreateSite { #[tracing::instrument(skip(context))] async fn perform(&self, context: &Data) -> Result { let data: &CreateSite = self; - let local_user_view = local_user_view_from_jwt(&data.auth, context).await?; - let local_site = LocalSite::read(context.conn().await?).await?; + let local_site = LocalSite::read(context.pool()).await?; // Make sure user is an admin; other types of users should not create site data... is_admin(&local_user_view)?; @@ -75,7 +74,7 @@ impl PerformCrud for CreateSite { let site_id = local_site.site_id; - Site::update(context.conn().await?, site_id, &site_form).await?; + Site::update(context.pool(), site_id, &site_form).await?; let local_site_form = LocalSiteUpdateForm::builder() // Set the site setup to true @@ -100,7 +99,7 @@ impl PerformCrud for CreateSite { .captcha_difficulty(data.captcha_difficulty.clone()) .build(); - LocalSite::update(context.conn().await?, &local_site_form).await?; + LocalSite::update(context.pool(), &local_site_form).await?; let local_site_rate_limit_form = LocalSiteRateLimitUpdateForm::builder() .message(data.rate_limit_message) @@ -117,12 +116,12 @@ impl PerformCrud for CreateSite { .search_per_second(data.rate_limit_search_per_second) .build(); - LocalSiteRateLimit::update(context.conn().await?, &local_site_rate_limit_form).await?; + LocalSiteRateLimit::update(context.pool(), &local_site_rate_limit_form).await?; - let site_view = SiteView::read_local(context.conn().await?).await?; + let site_view = SiteView::read_local(context.pool()).await?; let new_taglines = data.taglines.clone(); - let taglines = Tagline::replace(context.conn().await?, local_site.id, new_taglines).await?; + let taglines = Tagline::replace(context.pool(), local_site.id, new_taglines).await?; let rate_limit_config = local_site_rate_limit_to_rate_limit_config(&site_view.local_site_rate_limit); diff --git a/crates/api_crud/src/site/read.rs b/crates/api_crud/src/site/read.rs index a07caea0f..f6c663ac0 100644 --- a/crates/api_crud/src/site/read.rs +++ b/crates/api_crud/src/site/read.rs @@ -32,9 +32,9 @@ impl PerformCrud for GetSite { async fn perform(&self, context: &Data) -> Result { let data: &GetSite = self; - let site_view = SiteView::read_local(context.conn().await?).await?; + let site_view = SiteView::read_local(context.pool()).await?; - let admins = PersonView::admins(context.conn().await?).await?; + let admins = PersonView::admins(context.pool()).await?; // Build the local user let my_user = if let Some(local_user_view) = @@ -43,25 +43,25 @@ impl PerformCrud for GetSite { let person_id = local_user_view.person.id; let local_user_id = local_user_view.local_user.id; - let follows = CommunityFollowerView::for_person(context.conn().await?, person_id) + let follows = CommunityFollowerView::for_person(context.pool(), person_id) .await .map_err(|e| LemmyError::from_error_message(e, "system_err_login"))?; let person_id = local_user_view.person.id; - let community_blocks = CommunityBlockView::for_person(context.conn().await?, person_id) + let community_blocks = CommunityBlockView::for_person(context.pool(), person_id) .await .map_err(|e| LemmyError::from_error_message(e, "system_err_login"))?; let person_id = local_user_view.person.id; - let person_blocks = PersonBlockView::for_person(context.conn().await?, person_id) + let person_blocks = PersonBlockView::for_person(context.pool(), person_id) .await .map_err(|e| LemmyError::from_error_message(e, "system_err_login"))?; - let moderates = CommunityModeratorView::for_person(context.conn().await?, person_id) + let moderates = CommunityModeratorView::for_person(context.pool(), person_id) .await .map_err(|e| LemmyError::from_error_message(e, "system_err_login"))?; - let discussion_languages = LocalUserLanguage::read(context.conn().await?, local_user_id) + let discussion_languages = LocalUserLanguage::read(context.pool(), local_user_id) .await .map_err(|e| LemmyError::from_error_message(e, "system_err_login"))?; @@ -77,11 +77,10 @@ impl PerformCrud for GetSite { None }; - let all_languages = Language::read_all(context.conn().await?).await?; - let discussion_languages = SiteLanguage::read_local_raw(context.conn().await?).await?; - let taglines = Tagline::get_all(context.conn().await?, site_view.local_site.id).await?; - let custom_emojis = - CustomEmojiView::get_all(context.conn().await?, site_view.local_site.id).await?; + let all_languages = Language::read_all(context.pool()).await?; + let discussion_languages = SiteLanguage::read_local_raw(context.pool()).await?; + let taglines = Tagline::get_all(context.pool(), site_view.local_site.id).await?; + let custom_emojis = CustomEmojiView::get_all(context.pool(), site_view.local_site.id).await?; Ok(GetSiteResponse { site_view, @@ -107,7 +106,7 @@ async fn local_user_settings_view_from_jwt_opt( .ok()? .claims; let local_user_id = LocalUserId(claims.sub); - let local_user_view = LocalUserView::read(context.conn().await.ok()?, local_user_id) + let local_user_view = LocalUserView::read(context.pool(), local_user_id) .await .ok()?; check_user_valid( diff --git a/crates/api_crud/src/site/update.rs b/crates/api_crud/src/site/update.rs index 666220bc7..c9f97e8df 100644 --- a/crates/api_crud/src/site/update.rs +++ b/crates/api_crud/src/site/update.rs @@ -46,7 +46,7 @@ impl PerformCrud for EditSite { async fn perform(&self, context: &Data) -> Result { let data: &EditSite = self; let local_user_view = local_user_view_from_jwt(&data.auth, context).await?; - let site_view = SiteView::read_local(context.conn().await?).await?; + let site_view = SiteView::read_local(context.pool()).await?; let local_site = site_view.local_site; let site = site_view.site; @@ -56,7 +56,7 @@ impl PerformCrud for EditSite { validate_update_payload(&local_site, data)?; if let Some(discussion_languages) = data.discussion_languages.clone() { - SiteLanguage::update(context.conn().await?, discussion_languages.clone(), &site).await?; + SiteLanguage::update(context.pool(), discussion_languages.clone(), &site).await?; } let site_form = SiteUpdateForm::builder() @@ -68,7 +68,7 @@ impl PerformCrud for EditSite { .updated(Some(Some(naive_now()))) .build(); - Site::update(context.conn().await?, site.id, &site_form) + Site::update(context.pool(), site.id, &site_form) .await // Ignore errors for all these, so as to not throw errors if no update occurs // Diesel will throw an error for empty update forms @@ -96,7 +96,7 @@ impl PerformCrud for EditSite { .reports_email_admins(data.reports_email_admins) .build(); - let update_local_site = LocalSite::update(context.conn().await?, &local_site_form) + let update_local_site = LocalSite::update(context.pool(), &local_site_form) .await .ok(); @@ -115,15 +115,15 @@ impl PerformCrud for EditSite { .search_per_second(data.rate_limit_search_per_second) .build(); - LocalSiteRateLimit::update(context.conn().await?, &local_site_rate_limit_form) + LocalSiteRateLimit::update(context.pool(), &local_site_rate_limit_form) .await .ok(); // Replace the blocked and allowed instances let allowed = data.allowed_instances.clone(); - FederationAllowList::replace(context.conn().await?, allowed).await?; + FederationAllowList::replace(context.pool(), allowed).await?; let blocked = data.blocked_instances.clone(); - FederationBlockList::replace(context.conn().await?, blocked).await?; + FederationBlockList::replace(context.pool(), blocked).await?; // TODO can't think of a better way to do this. // If the server suddenly requires email verification, or required applications, no old users @@ -137,7 +137,7 @@ impl PerformCrud for EditSite { .map(|ols| ols.registration_mode == RegistrationMode::RequireApplication) .unwrap_or(false); if !old_require_application && new_require_application { - LocalUser::set_all_users_registration_applications_accepted(context.conn().await?) + LocalUser::set_all_users_registration_applications_accepted(context.pool()) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_set_all_registrations_accepted"))?; } @@ -147,15 +147,15 @@ impl PerformCrud for EditSite { .map(|ols| ols.require_email_verification) .unwrap_or(false); if !local_site.require_email_verification && new_require_email_verification { - LocalUser::set_all_users_email_verified(context.conn().await?) + LocalUser::set_all_users_email_verified(context.pool()) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_set_all_email_verified"))?; } let new_taglines = data.taglines.clone(); - let taglines = Tagline::replace(context.conn().await?, local_site.id, new_taglines).await?; + let taglines = Tagline::replace(context.pool(), local_site.id, new_taglines).await?; - let site_view = SiteView::read_local(context.conn().await?).await?; + let site_view = SiteView::read_local(context.pool()).await?; let rate_limit_config = local_site_rate_limit_to_rate_limit_config(&site_view.local_site_rate_limit); diff --git a/crates/api_crud/src/user/create.rs b/crates/api_crud/src/user/create.rs index 6c729ca13..302e2f98e 100644 --- a/crates/api_crud/src/user/create.rs +++ b/crates/api_crud/src/user/create.rs @@ -45,7 +45,7 @@ impl PerformCrud for Register { async fn perform(&self, context: &Data) -> Result { let data: &Register = self; - let site_view = SiteView::read_local(context.conn().await?).await?; + let site_view = SiteView::read_local(context.pool()).await?; let local_site = site_view.local_site; let require_registration_application = local_site.registration_mode == RegistrationMode::RequireApplication; @@ -76,7 +76,7 @@ impl PerformCrud for Register { if let Some(captcha_uuid) = &data.captcha_uuid { let uuid = uuid::Uuid::parse_str(captcha_uuid)?; let check = CaptchaAnswer::check_captcha( - context.conn().await?, + context.pool(), CheckCaptchaAnswer { uuid, answer: data.captcha_answer.clone().unwrap_or_default(), @@ -104,7 +104,7 @@ impl PerformCrud for Register { )?; if let Some(email) = &data.email { - if LocalUser::is_email_taken(context.conn().await?, email).await? { + if LocalUser::is_email_taken(context.pool(), email).await? { return Err(LemmyError::from_message("email_already_exists")); } } @@ -125,7 +125,7 @@ impl PerformCrud for Register { .build(); // insert the person - let inserted_person = Person::create(context.conn().await?, &person_form) + let inserted_person = Person::create(context.pool(), &person_form) .await .map_err(|e| LemmyError::from_error_message(e, "user_already_exists"))?; @@ -142,7 +142,7 @@ impl PerformCrud for Register { .accepted_application(accepted_application) .build(); - let inserted_local_user = LocalUser::create(context.conn().await?, &local_user_form).await?; + let inserted_local_user = LocalUser::create(context.pool(), &local_user_form).await?; if local_site.site_setup && require_registration_application { // Create the registration application @@ -152,12 +152,12 @@ impl PerformCrud for Register { answer: data.answer.clone().expect("must have an answer"), }; - RegistrationApplication::create(context.conn().await?, &form).await?; + RegistrationApplication::create(context.pool(), &form).await?; } // Email the admins if local_site.application_email_admins { - send_new_applicant_email_to_admins(&data.username, context.conn().await?, context.settings()) + send_new_applicant_email_to_admins(&data.username, context.pool(), context.settings()) .await?; } @@ -193,13 +193,8 @@ impl PerformCrud for Register { .clone() .expect("email was provided"); - send_verification_email( - &local_user_view, - &email, - context.conn().await?, - context.settings(), - ) - .await?; + send_verification_email(&local_user_view, &email, context.pool(), context.settings()) + .await?; login_response.verify_email_sent = true; } diff --git a/crates/apub/src/activities/block/block_user.rs b/crates/apub/src/activities/block/block_user.rs index 7ae0ed925..46f9b7940 100644 --- a/crates/apub/src/activities/block/block_user.rs +++ b/crates/apub/src/activities/block/block_user.rs @@ -60,7 +60,7 @@ impl BlockUser { actor: mod_.id().into(), to: vec![public()], object: user.id().into(), - cc: generate_cc(target, context.conn().await?).await?, + cc: generate_cc(target, context.pool()).await?, target: target.id(), kind: BlockType::Block, remove_data, @@ -97,7 +97,7 @@ impl BlockUser { match target { SiteOrCommunity::Site(_) => { - let inboxes = remote_instance_inboxes(context.conn().await?).await?; + let inboxes = remote_instance_inboxes(context.pool()).await?; send_lemmy_activity(context, block, mod_, inboxes, false).await } SiteOrCommunity::Community(c) => { @@ -155,7 +155,7 @@ impl ActivityHandler for BlockUser { match target { SiteOrCommunity::Site(_site) => { let blocked_person = Person::update( - context.conn().await?, + context.pool(), blocked_person.id, &PersonUpdateForm::builder() .banned(Some(true)) @@ -181,7 +181,7 @@ impl ActivityHandler for BlockUser { banned: Some(true), expires, }; - ModBan::create(context.conn().await?, &form).await?; + ModBan::create(context.pool(), &form).await?; } SiteOrCommunity::Community(community) => { let community_user_ban_form = CommunityPersonBanForm { @@ -189,7 +189,7 @@ impl ActivityHandler for BlockUser { person_id: blocked_person.id, expires: Some(expires), }; - CommunityPersonBan::ban(context.conn().await?, &community_user_ban_form).await?; + CommunityPersonBan::ban(context.pool(), &community_user_ban_form).await?; // Also unsubscribe them from the community, if they are subscribed let community_follower_form = CommunityFollowerForm { @@ -197,7 +197,7 @@ impl ActivityHandler for BlockUser { person_id: blocked_person.id, pending: false, }; - CommunityFollower::unfollow(context.conn().await?, &community_follower_form) + CommunityFollower::unfollow(context.pool(), &community_follower_form) .await .ok(); @@ -214,7 +214,7 @@ impl ActivityHandler for BlockUser { banned: Some(true), expires, }; - ModBanFromCommunity::create(context.conn().await?, &form).await?; + ModBanFromCommunity::create(context.pool(), &form).await?; } } diff --git a/crates/apub/src/activities/block/mod.rs b/crates/apub/src/activities/block/mod.rs index b725d615a..a791ea40e 100644 --- a/crates/apub/src/activities/block/mod.rs +++ b/crates/apub/src/activities/block/mod.rs @@ -21,7 +21,7 @@ use lemmy_api_common::{ use lemmy_db_schema::{ source::{community::Community, person::Person, site::Site}, traits::Crud, - utils::GetConn, + utils::DbPool, }; use lemmy_db_views::structs::SiteView; use lemmy_utils::{error::LemmyError, utils::time::naive_from_unix}; @@ -118,9 +118,9 @@ impl SiteOrCommunity { } } -async fn generate_cc(target: &SiteOrCommunity, conn: impl GetConn) -> Result, LemmyError> { +async fn generate_cc(target: &SiteOrCommunity, pool: &DbPool) -> Result, LemmyError> { Ok(match target { - SiteOrCommunity::Site(_) => Site::read_remote_sites(conn) + SiteOrCommunity::Site(_) => Site::read_remote_sites(pool) .await? .into_iter() .map(|s| s.actor_id.into()) @@ -139,13 +139,8 @@ impl SendActivity for BanPerson { context: &Data, ) -> Result<(), LemmyError> { let local_user_view = local_user_view_from_jwt(&request.auth, context).await?; - let person = Person::read(context.conn().await?, request.person_id).await?; - let site = SiteOrCommunity::Site( - SiteView::read_local(context.conn().await?) - .await? - .site - .into(), - ); + let person = Person::read(context.pool(), request.person_id).await?; + let site = SiteOrCommunity::Site(SiteView::read_local(context.pool()).await?.site.into()); let expires = request.expires.map(naive_from_unix); // if the action affects a local user, federate to other instances @@ -187,10 +182,10 @@ impl SendActivity for BanFromCommunity { context: &Data, ) -> Result<(), LemmyError> { let local_user_view = local_user_view_from_jwt(&request.auth, context).await?; - let community: ApubCommunity = Community::read(context.conn().await?, request.community_id) + let community: ApubCommunity = Community::read(context.pool(), request.community_id) .await? .into(); - let banned_person: ApubPerson = Person::read(context.conn().await?, request.person_id) + let banned_person: ApubPerson = Person::read(context.pool(), request.person_id) .await? .into(); let expires = request.expires.map(naive_from_unix); diff --git a/crates/apub/src/activities/block/undo_block_user.rs b/crates/apub/src/activities/block/undo_block_user.rs index f1a15cb0b..43bc73523 100644 --- a/crates/apub/src/activities/block/undo_block_user.rs +++ b/crates/apub/src/activities/block/undo_block_user.rs @@ -53,7 +53,7 @@ impl UndoBlockUser { actor: mod_.id().into(), to: vec![public()], object: block, - cc: generate_cc(target, context.conn().await?).await?, + cc: generate_cc(target, context.pool()).await?, kind: UndoType::Undo, id: id.clone(), audience, @@ -62,7 +62,7 @@ impl UndoBlockUser { let mut inboxes = vec![user.shared_inbox_or_inbox()]; match target { SiteOrCommunity::Site(_) => { - inboxes.append(&mut remote_instance_inboxes(context.conn().await?).await?); + inboxes.append(&mut remote_instance_inboxes(context.pool()).await?); send_lemmy_activity(context, undo, mod_, inboxes, false).await } SiteOrCommunity::Community(c) => { @@ -103,7 +103,7 @@ impl ActivityHandler for UndoBlockUser { match self.object.target.dereference(context).await? { SiteOrCommunity::Site(_site) => { let blocked_person = Person::update( - context.conn().await?, + context.pool(), blocked_person.id, &PersonUpdateForm::builder() .banned(Some(false)) @@ -120,7 +120,7 @@ impl ActivityHandler for UndoBlockUser { banned: Some(false), expires, }; - ModBan::create(context.conn().await?, &form).await?; + ModBan::create(context.pool(), &form).await?; } SiteOrCommunity::Community(community) => { let community_user_ban_form = CommunityPersonBanForm { @@ -128,7 +128,7 @@ impl ActivityHandler for UndoBlockUser { person_id: blocked_person.id, expires: None, }; - CommunityPersonBan::unban(context.conn().await?, &community_user_ban_form).await?; + CommunityPersonBan::unban(context.pool(), &community_user_ban_form).await?; // write to mod log let form = ModBanFromCommunityForm { @@ -139,7 +139,7 @@ impl ActivityHandler for UndoBlockUser { banned: Some(false), expires, }; - ModBanFromCommunity::create(context.conn().await?, &form).await?; + ModBanFromCommunity::create(context.pool(), &form).await?; } } diff --git a/crates/apub/src/activities/community/collection_add.rs b/crates/apub/src/activities/community/collection_add.rs index 8ceba20e7..be5dd0fe3 100644 --- a/crates/apub/src/activities/community/collection_add.rs +++ b/crates/apub/src/activities/community/collection_add.rs @@ -119,7 +119,7 @@ impl ActivityHandler for CollectionAdd { async fn receive(self, context: &Data) -> Result<(), LemmyError> { insert_activity(&self.id, &self, false, false, context).await?; let (community, collection_type) = - Community::get_by_collection_url(context.conn().await?, &self.target.into()).await?; + Community::get_by_collection_url(context.pool(), &self.target.into()).await?; match collection_type { CollectionType::Moderators => { let new_mod = ObjectId::::from(self.object) @@ -130,14 +130,13 @@ impl ActivityHandler for CollectionAdd { // been added. Skip it here as it would result in a duplicate key error. let new_mod_id = new_mod.id; let moderated_communities = - CommunityModerator::get_person_moderated_communities(context.conn().await?, new_mod_id) - .await?; + CommunityModerator::get_person_moderated_communities(context.pool(), new_mod_id).await?; if !moderated_communities.contains(&community.id) { let form = CommunityModeratorForm { community_id: community.id, person_id: new_mod.id, }; - CommunityModerator::join(context.conn().await?, &form).await?; + CommunityModerator::join(context.pool(), &form).await?; // write mod log let actor = self.actor.dereference(context).await?; @@ -147,7 +146,7 @@ impl ActivityHandler for CollectionAdd { community_id: community.id, removed: Some(false), }; - ModAddCommunity::create(context.conn().await?, &form).await?; + ModAddCommunity::create(context.pool(), &form).await?; } // TODO: send websocket notification about added mod } @@ -158,7 +157,7 @@ impl ActivityHandler for CollectionAdd { let form = PostUpdateForm::builder() .featured_community(Some(true)) .build(); - Post::update(context.conn().await?, post.id, &form).await?; + Post::update(context.pool(), post.id, &form).await?; } } Ok(()) @@ -175,10 +174,10 @@ impl SendActivity for AddModToCommunity { context: &Data, ) -> Result<(), LemmyError> { let local_user_view = local_user_view_from_jwt(&request.auth, context).await?; - let community: ApubCommunity = Community::read(context.conn().await?, request.community_id) + let community: ApubCommunity = Community::read(context.pool(), request.community_id) .await? .into(); - let updated_mod: ApubPerson = Person::read(context.conn().await?, request.person_id) + let updated_mod: ApubPerson = Person::read(context.pool(), request.person_id) .await? .into(); if request.added { @@ -211,7 +210,7 @@ impl SendActivity for FeaturePost { context: &Data, ) -> Result<(), LemmyError> { let local_user_view = local_user_view_from_jwt(&request.auth, context).await?; - let community = Community::read(context.conn().await?, response.post_view.community.id) + let community = Community::read(context.pool(), response.post_view.community.id) .await? .into(); let post = response.post_view.post.clone().into(); diff --git a/crates/apub/src/activities/community/collection_remove.rs b/crates/apub/src/activities/community/collection_remove.rs index d6e67be27..8f920cf24 100644 --- a/crates/apub/src/activities/community/collection_remove.rs +++ b/crates/apub/src/activities/community/collection_remove.rs @@ -112,7 +112,7 @@ impl ActivityHandler for CollectionRemove { async fn receive(self, context: &Data) -> Result<(), LemmyError> { insert_activity(&self.id, &self, false, false, context).await?; let (community, collection_type) = - Community::get_by_collection_url(context.conn().await?, &self.target.into()).await?; + Community::get_by_collection_url(context.pool(), &self.target.into()).await?; match collection_type { CollectionType::Moderators => { let remove_mod = ObjectId::::from(self.object) @@ -123,7 +123,7 @@ impl ActivityHandler for CollectionRemove { community_id: community.id, person_id: remove_mod.id, }; - CommunityModerator::leave(context.conn().await?, &form).await?; + CommunityModerator::leave(context.pool(), &form).await?; // write mod log let actor = self.actor.dereference(context).await?; @@ -133,7 +133,7 @@ impl ActivityHandler for CollectionRemove { community_id: community.id, removed: Some(true), }; - ModAddCommunity::create(context.conn().await?, &form).await?; + ModAddCommunity::create(context.pool(), &form).await?; // TODO: send websocket notification about removed mod } @@ -144,7 +144,7 @@ impl ActivityHandler for CollectionRemove { let form = PostUpdateForm::builder() .featured_community(Some(false)) .build(); - Post::update(context.conn().await?, post.id, &form).await?; + Post::update(context.pool(), post.id, &form).await?; } } Ok(()) diff --git a/crates/apub/src/activities/community/lock_page.rs b/crates/apub/src/activities/community/lock_page.rs index 3b460f9f3..5e4eefb81 100644 --- a/crates/apub/src/activities/community/lock_page.rs +++ b/crates/apub/src/activities/community/lock_page.rs @@ -60,7 +60,7 @@ impl ActivityHandler for LockPage { async fn receive(self, context: &Data) -> Result<(), Self::Error> { let form = PostUpdateForm::builder().locked(Some(true)).build(); let post = self.object.dereference(context).await?; - Post::update(context.conn().await?, post.id, &form).await?; + Post::update(context.pool(), post.id, &form).await?; Ok(()) } } @@ -97,7 +97,7 @@ impl ActivityHandler for UndoLockPage { insert_activity(&self.id, &self, false, false, context).await?; let form = PostUpdateForm::builder().locked(Some(false)).build(); let post = self.object.object.dereference(context).await?; - Post::update(context.conn().await?, post.id, &form).await?; + Post::update(context.pool(), post.id, &form).await?; Ok(()) } } @@ -145,7 +145,7 @@ impl SendActivity for LockPost { }; AnnouncableActivities::UndoLockPost(undo) }; - let community = Community::read(context.conn().await?, response.post_view.community.id).await?; + let community = Community::read(context.pool(), response.post_view.community.id).await?; send_activity_in_community( activity, &local_user_view.person.into(), diff --git a/crates/apub/src/activities/community/mod.rs b/crates/apub/src/activities/community/mod.rs index 3555437a8..010bad4f4 100644 --- a/crates/apub/src/activities/community/mod.rs +++ b/crates/apub/src/activities/community/mod.rs @@ -44,7 +44,7 @@ pub(crate) async fn send_activity_in_community( // send to user followers if !is_mod_action { inboxes.extend( - &mut PersonFollower::list_followers(context.conn().await?, actor.id) + &mut PersonFollower::list_followers(context.pool(), actor.id) .await? .into_iter() .map(|p| ApubPerson(p).shared_inbox_or_inbox()), diff --git a/crates/apub/src/activities/community/report.rs b/crates/apub/src/activities/community/report.rs index f46d25a1f..750672edb 100644 --- a/crates/apub/src/activities/community/report.rs +++ b/crates/apub/src/activities/community/report.rs @@ -134,7 +134,7 @@ impl ActivityHandler for Report { reason: self.summary, original_post_body: post.body.clone(), }; - PostReport::report(context.conn().await?, &report_form).await?; + PostReport::report(context.pool(), &report_form).await?; } PostOrComment::Comment(comment) => { let report_form = CommentReportForm { @@ -143,7 +143,7 @@ impl ActivityHandler for Report { original_comment_text: comment.content.clone(), reason: self.summary, }; - CommentReport::report(context.conn().await?, &report_form).await?; + CommentReport::report(context.pool(), &report_form).await?; } }; Ok(()) diff --git a/crates/apub/src/activities/community/update.rs b/crates/apub/src/activities/community/update.rs index f5f10aa18..f8bbfa6ce 100644 --- a/crates/apub/src/activities/community/update.rs +++ b/crates/apub/src/activities/community/update.rs @@ -36,7 +36,7 @@ impl SendActivity for EditCommunity { context: &Data, ) -> Result<(), LemmyError> { let local_user_view = local_user_view_from_jwt(&request.auth, context).await?; - let community = Community::read(context.conn().await?, request.community_id).await?; + let community = Community::read(context.pool(), request.community_id).await?; UpdateCommunity::send(community.into(), &local_user_view.person.into(), context).await } } @@ -97,7 +97,7 @@ impl ActivityHandler for UpdateCommunity { let community_update_form = self.object.into_update_form(); - Community::update(context.conn().await?, community.id, &community_update_form).await?; + Community::update(context.pool(), community.id, &community_update_form).await?; Ok(()) } } @@ -112,7 +112,7 @@ impl SendActivity for HideCommunity { context: &Data, ) -> Result<(), LemmyError> { let local_user_view = local_user_view_from_jwt(&request.auth, context).await?; - let community = Community::read(context.conn().await?, request.community_id).await?; + let community = Community::read(context.pool(), request.community_id).await?; UpdateCommunity::send(community.into(), &local_user_view.person.into(), context).await } } diff --git a/crates/apub/src/activities/create_or_update/comment.rs b/crates/apub/src/activities/create_or_update/comment.rs index cfbef4e30..e9e567335 100644 --- a/crates/apub/src/activities/create_or_update/comment.rs +++ b/crates/apub/src/activities/create_or_update/comment.rs @@ -91,12 +91,10 @@ impl CreateOrUpdateNote { ) -> Result<(), LemmyError> { // TODO: might be helpful to add a comment method to retrieve community directly let post_id = comment.post_id; - let post = Post::read(context.conn().await?, post_id).await?; + let post = Post::read(context.pool(), post_id).await?; let community_id = post.community_id; - let person: ApubPerson = Person::read(context.conn().await?, person_id).await?.into(); - let community: ApubCommunity = Community::read(context.conn().await?, community_id) - .await? - .into(); + let person: ApubPerson = Person::read(context.pool(), person_id).await?.into(); + let community: ApubCommunity = Community::read(context.pool(), community_id).await?.into(); let id = generate_activity_id( kind.clone(), @@ -179,7 +177,7 @@ impl ActivityHandler for CreateOrUpdateNote { if distinguished != existing_comment.distinguished { let creator = self.actor.dereference(context).await?; let (post, _) = self.object.get_parents(context).await?; - is_mod_or_admin(context.conn().await?, creator.id, post.community_id).await?; + is_mod_or_admin(context.pool(), creator.id, post.community_id).await?; } } @@ -192,14 +190,14 @@ impl ActivityHandler for CreateOrUpdateNote { person_id: comment.creator_id, score: 1, }; - CommentLike::like(context.conn().await?, &like_form).await?; + CommentLike::like(context.pool(), &like_form).await?; // Calculate initial hot_rank - CommentAggregates::update_hot_rank(context.conn().await?, comment.id).await?; + CommentAggregates::update_hot_rank(context.pool(), comment.id).await?; let do_send_email = self.kind == CreateOrUpdateType::Create; let post_id = comment.post_id; - let post = Post::read(context.conn().await?, post_id).await?; + let post = Post::read(context.pool(), post_id).await?; let actor = self.actor.dereference(context).await?; // Note: diff --git a/crates/apub/src/activities/create_or_update/post.rs b/crates/apub/src/activities/create_or_update/post.rs index 385b80e51..916111fc5 100644 --- a/crates/apub/src/activities/create_or_update/post.rs +++ b/crates/apub/src/activities/create_or_update/post.rs @@ -109,10 +109,8 @@ impl CreateOrUpdatePage { ) -> Result<(), LemmyError> { let post = ApubPost(post.clone()); let community_id = post.community_id; - let person: ApubPerson = Person::read(context.conn().await?, person_id).await?.into(); - let community: ApubCommunity = Community::read(context.conn().await?, community_id) - .await? - .into(); + let person: ApubPerson = Person::read(context.pool(), person_id).await?.into(); + let community: ApubCommunity = Community::read(context.pool(), community_id).await?.into(); let create_or_update = CreateOrUpdatePage::new(post, &person, &community, kind, context).await?; @@ -189,10 +187,10 @@ impl ActivityHandler for CreateOrUpdatePage { person_id: post.creator_id, score: 1, }; - PostLike::like(context.conn().await?, &like_form).await?; + PostLike::like(context.pool(), &like_form).await?; // Calculate initial hot_rank for post - PostAggregates::update_hot_rank(context.conn().await?, post.id).await?; + PostAggregates::update_hot_rank(context.pool(), post.id).await?; Ok(()) } diff --git a/crates/apub/src/activities/create_or_update/private_message.rs b/crates/apub/src/activities/create_or_update/private_message.rs index 22a2321b3..691eff300 100644 --- a/crates/apub/src/activities/create_or_update/private_message.rs +++ b/crates/apub/src/activities/create_or_update/private_message.rs @@ -71,10 +71,8 @@ impl CreateOrUpdateChatMessage { context: &Data, ) -> Result<(), LemmyError> { let recipient_id = private_message.recipient_id; - let sender: ApubPerson = Person::read(context.conn().await?, sender_id).await?.into(); - let recipient: ApubPerson = Person::read(context.conn().await?, recipient_id) - .await? - .into(); + let sender: ApubPerson = Person::read(context.pool(), sender_id).await?.into(); + let recipient: ApubPerson = Person::read(context.pool(), recipient_id).await?.into(); let id = generate_activity_id( kind.clone(), diff --git a/crates/apub/src/activities/deletion/delete.rs b/crates/apub/src/activities/deletion/delete.rs index 56fd1e885..dfa709c36 100644 --- a/crates/apub/src/activities/deletion/delete.rs +++ b/crates/apub/src/activities/deletion/delete.rs @@ -119,9 +119,9 @@ pub(in crate::activities) async fn receive_remove_action( reason, expires: None, }; - ModRemoveCommunity::create(context.conn().await?, &form).await?; + ModRemoveCommunity::create(context.pool(), &form).await?; Community::update( - context.conn().await?, + context.pool(), community.id, &CommunityUpdateForm::builder().removed(Some(true)).build(), ) @@ -134,9 +134,9 @@ pub(in crate::activities) async fn receive_remove_action( removed: Some(true), reason, }; - ModRemovePost::create(context.conn().await?, &form).await?; + ModRemovePost::create(context.pool(), &form).await?; Post::update( - context.conn().await?, + context.pool(), post.id, &PostUpdateForm::builder().removed(Some(true)).build(), ) @@ -149,9 +149,9 @@ pub(in crate::activities) async fn receive_remove_action( removed: Some(true), reason, }; - ModRemoveComment::create(context.conn().await?, &form).await?; + ModRemoveComment::create(context.pool(), &form).await?; Comment::update( - context.conn().await?, + context.pool(), comment.id, &CommentUpdateForm::builder().removed(Some(true)).build(), ) diff --git a/crates/apub/src/activities/deletion/delete_user.rs b/crates/apub/src/activities/deletion/delete_user.rs index 3aef5abb9..11be132e8 100644 --- a/crates/apub/src/activities/deletion/delete_user.rs +++ b/crates/apub/src/activities/deletion/delete_user.rs @@ -51,7 +51,7 @@ impl SendActivity for DeleteAccount { cc: vec![], }; - let inboxes = remote_instance_inboxes(context.conn().await?).await?; + let inboxes = remote_instance_inboxes(context.pool()).await?; send_lemmy_activity(context, delete, &actor, inboxes, true).await?; Ok(()) } diff --git a/crates/apub/src/activities/deletion/mod.rs b/crates/apub/src/activities/deletion/mod.rs index 35a1c8d96..3bde90f93 100644 --- a/crates/apub/src/activities/deletion/mod.rs +++ b/crates/apub/src/activities/deletion/mod.rs @@ -64,7 +64,7 @@ impl SendActivity for DeletePost { context: &Data, ) -> Result<(), LemmyError> { let local_user_view = local_user_view_from_jwt(&request.auth, context).await?; - let community = Community::read(context.conn().await?, response.post_view.community.id).await?; + let community = Community::read(context.pool(), response.post_view.community.id).await?; let deletable = DeletableObjects::Post(response.post_view.post.clone().into()); send_apub_delete_in_community( local_user_view.person, @@ -88,7 +88,7 @@ impl SendActivity for RemovePost { context: &Data, ) -> Result<(), LemmyError> { let local_user_view = local_user_view_from_jwt(&request.auth, context).await?; - let community = Community::read(context.conn().await?, response.post_view.community.id).await?; + let community = Community::read(context.pool(), response.post_view.community.id).await?; let deletable = DeletableObjects::Post(response.post_view.post.clone().into()); send_apub_delete_in_community( local_user_view.person, @@ -112,8 +112,8 @@ impl SendActivity for DeleteComment { context: &Data, ) -> Result<(), LemmyError> { let community_id = response.comment_view.community.id; - let community = Community::read(context.conn().await?, community_id).await?; - let person = Person::read(context.conn().await?, response.comment_view.creator.id).await?; + let community = Community::read(context.pool(), community_id).await?; + let person = Person::read(context.pool(), response.comment_view.creator.id).await?; let deletable = DeletableObjects::Comment(response.comment_view.comment.clone().into()); send_apub_delete_in_community(person, community, deletable, None, request.deleted, context) .await @@ -130,9 +130,8 @@ impl SendActivity for RemoveComment { context: &Data, ) -> Result<(), LemmyError> { let local_user_view = local_user_view_from_jwt(&request.auth, context).await?; - let comment = Comment::read(context.conn().await?, request.comment_id).await?; - let community = - Community::read(context.conn().await?, response.comment_view.community.id).await?; + let comment = Comment::read(context.pool(), request.comment_id).await?; + let community = Community::read(context.pool(), response.comment_view.community.id).await?; let deletable = DeletableObjects::Comment(comment.into()); send_apub_delete_in_community( local_user_view.person, @@ -176,7 +175,7 @@ impl SendActivity for DeleteCommunity { context: &Data, ) -> Result<(), LemmyError> { let local_user_view = local_user_view_from_jwt(&request.auth, context).await?; - let community = Community::read(context.conn().await?, request.community_id).await?; + let community = Community::read(context.pool(), request.community_id).await?; let deletable = DeletableObjects::Community(community.clone().into()); send_apub_delete_in_community( local_user_view.person, @@ -200,7 +199,7 @@ impl SendActivity for RemoveCommunity { context: &Data, ) -> Result<(), LemmyError> { let local_user_view = local_user_view_from_jwt(&request.auth, context).await?; - let community = Community::read(context.conn().await?, request.community_id).await?; + let community = Community::read(context.pool(), request.community_id).await?; let deletable = DeletableObjects::Community(community.clone().into()); send_apub_delete_in_community( local_user_view.person, @@ -253,9 +252,7 @@ async fn send_apub_delete_private_message( context: &Data, ) -> Result<(), LemmyError> { let recipient_id = pm.recipient_id; - let recipient: ApubPerson = Person::read(context.conn().await?, recipient_id) - .await? - .into(); + let recipient: ApubPerson = Person::read(context.pool(), recipient_id).await?.into(); let deletable = DeletableObjects::PrivateMessage(pm.into()); let inbox = vec![recipient.shared_inbox_or_inbox()]; @@ -391,7 +388,7 @@ async fn receive_delete_action( } Community::update( - context.conn().await?, + context.pool(), community.id, &CommunityUpdateForm::builder() .deleted(Some(deleted)) @@ -402,7 +399,7 @@ async fn receive_delete_action( DeletableObjects::Post(post) => { if deleted != post.deleted { Post::update( - context.conn().await?, + context.pool(), post.id, &PostUpdateForm::builder().deleted(Some(deleted)).build(), ) @@ -412,7 +409,7 @@ async fn receive_delete_action( DeletableObjects::Comment(comment) => { if deleted != comment.deleted { Comment::update( - context.conn().await?, + context.pool(), comment.id, &CommentUpdateForm::builder().deleted(Some(deleted)).build(), ) @@ -421,7 +418,7 @@ async fn receive_delete_action( } DeletableObjects::PrivateMessage(pm) => { PrivateMessage::update( - context.conn().await?, + context.pool(), pm.id, &PrivateMessageUpdateForm::builder() .deleted(Some(deleted)) diff --git a/crates/apub/src/activities/deletion/undo_delete.rs b/crates/apub/src/activities/deletion/undo_delete.rs index 916a36fa7..00768580d 100644 --- a/crates/apub/src/activities/deletion/undo_delete.rs +++ b/crates/apub/src/activities/deletion/undo_delete.rs @@ -111,9 +111,9 @@ impl UndoDelete { reason: None, expires: None, }; - ModRemoveCommunity::create(context.conn().await?, &form).await?; + ModRemoveCommunity::create(context.pool(), &form).await?; Community::update( - context.conn().await?, + context.pool(), community.id, &CommunityUpdateForm::builder().removed(Some(false)).build(), ) @@ -126,9 +126,9 @@ impl UndoDelete { removed: Some(false), reason: None, }; - ModRemovePost::create(context.conn().await?, &form).await?; + ModRemovePost::create(context.pool(), &form).await?; Post::update( - context.conn().await?, + context.pool(), post.id, &PostUpdateForm::builder().removed(Some(false)).build(), ) @@ -141,9 +141,9 @@ impl UndoDelete { removed: Some(false), reason: None, }; - ModRemoveComment::create(context.conn().await?, &form).await?; + ModRemoveComment::create(context.pool(), &form).await?; Comment::update( - context.conn().await?, + context.pool(), comment.id, &CommentUpdateForm::builder().removed(Some(false)).build(), ) diff --git a/crates/apub/src/activities/following/accept.rs b/crates/apub/src/activities/following/accept.rs index 7bf38cd7b..7b9ab6802 100644 --- a/crates/apub/src/activities/following/accept.rs +++ b/crates/apub/src/activities/following/accept.rs @@ -66,7 +66,7 @@ impl ActivityHandler for AcceptFollow { // This will throw an error if no follow was requested let community_id = community.id; let person_id = person.id; - CommunityFollower::follow_accepted(context.conn().await?, community_id, person_id).await?; + CommunityFollower::follow_accepted(context.pool(), community_id, person_id).await?; Ok(()) } diff --git a/crates/apub/src/activities/following/follow.rs b/crates/apub/src/activities/following/follow.rs index 2b0d987da..8a785da05 100644 --- a/crates/apub/src/activities/following/follow.rs +++ b/crates/apub/src/activities/following/follow.rs @@ -65,7 +65,7 @@ impl Follow { person_id: actor.id, pending: true, }; - CommunityFollower::follow(context.conn().await?, &community_follower_form) + CommunityFollower::follow(context.pool(), &community_follower_form) .await .ok(); @@ -113,7 +113,7 @@ impl ActivityHandler for Follow { follower_id: actor.id, pending: false, }; - PersonFollower::follow(context.conn().await?, &form).await?; + PersonFollower::follow(context.pool(), &form).await?; } UserOrCommunity::Community(c) => { let form = CommunityFollowerForm { @@ -121,7 +121,7 @@ impl ActivityHandler for Follow { person_id: actor.id, pending: false, }; - CommunityFollower::follow(context.conn().await?, &form).await?; + CommunityFollower::follow(context.pool(), &form).await?; } } @@ -139,7 +139,7 @@ impl SendActivity for BlockCommunity { context: &Data, ) -> Result<(), LemmyError> { let local_user_view = local_user_view_from_jwt(&request.auth, context).await?; - let community = Community::read(context.conn().await?, request.community_id).await?; + let community = Community::read(context.pool(), request.community_id).await?; UndoFollow::send(&local_user_view.person.into(), &community.into(), context).await } } diff --git a/crates/apub/src/activities/following/mod.rs b/crates/apub/src/activities/following/mod.rs index 67e000b64..a4c2fd673 100644 --- a/crates/apub/src/activities/following/mod.rs +++ b/crates/apub/src/activities/following/mod.rs @@ -27,7 +27,7 @@ impl SendActivity for FollowCommunity { ) -> Result<(), LemmyError> { let local_user_view = local_user_view_from_jwt(&request.auth, context).await?; let person = local_user_view.person.clone().into(); - let community: ApubCommunity = Community::read(context.conn().await?, request.community_id) + let community: ApubCommunity = Community::read(context.pool(), request.community_id) .await? .into(); if community.local { diff --git a/crates/apub/src/activities/following/undo_follow.rs b/crates/apub/src/activities/following/undo_follow.rs index a1d4392f4..279054d53 100644 --- a/crates/apub/src/activities/following/undo_follow.rs +++ b/crates/apub/src/activities/following/undo_follow.rs @@ -82,7 +82,7 @@ impl ActivityHandler for UndoFollow { follower_id: person.id, pending: false, }; - PersonFollower::unfollow(context.conn().await?, &form).await?; + PersonFollower::unfollow(context.pool(), &form).await?; } UserOrCommunity::Community(c) => { let form = CommunityFollowerForm { @@ -90,7 +90,7 @@ impl ActivityHandler for UndoFollow { person_id: person.id, pending: false, }; - CommunityFollower::unfollow(context.conn().await?, &form).await?; + CommunityFollower::unfollow(context.pool(), &form).await?; } } diff --git a/crates/apub/src/activities/mod.rs b/crates/apub/src/activities/mod.rs index b38e3a1c6..4b50c5c83 100644 --- a/crates/apub/src/activities/mod.rs +++ b/crates/apub/src/activities/mod.rs @@ -59,7 +59,7 @@ pub(crate) async fn verify_person_in_community( } let person_id = person.id; let community_id = community.id; - let is_banned = CommunityPersonBanView::get(context.conn().await?, person_id, community_id) + let is_banned = CommunityPersonBanView::get(context.pool(), person_id, community_id) .await .is_ok(); if is_banned { @@ -84,7 +84,7 @@ pub(crate) async fn verify_mod_action( let mod_ = mod_id.dereference(context).await?; let is_mod_or_admin = - CommunityView::is_mod_or_admin(context.conn().await?, mod_.id, community_id).await?; + CommunityView::is_mod_or_admin(context.pool(), mod_.id, community_id).await?; if is_mod_or_admin { return Ok(()); } diff --git a/crates/apub/src/activities/voting/mod.rs b/crates/apub/src/activities/voting/mod.rs index ccf11bcab..8bae05577 100644 --- a/crates/apub/src/activities/voting/mod.rs +++ b/crates/apub/src/activities/voting/mod.rs @@ -83,11 +83,9 @@ async fn send_activity( jwt: &Sensitive, context: &Data, ) -> Result<(), LemmyError> { - let community = Community::read(context.conn().await?, community_id) - .await? - .into(); + let community = Community::read(context.pool(), community_id).await?.into(); let local_user_view = local_user_view_from_jwt(jwt, context).await?; - let actor = Person::read(context.conn().await?, local_user_view.person.id) + let actor = Person::read(context.pool(), local_user_view.person.id) .await? .into(); @@ -120,8 +118,8 @@ async fn vote_comment( score: vote_type.into(), }; let person_id = actor.id; - CommentLike::remove(context.conn().await?, person_id, comment_id).await?; - CommentLike::like(context.conn().await?, &like_form).await?; + CommentLike::remove(context.pool(), person_id, comment_id).await?; + CommentLike::like(context.pool(), &like_form).await?; Ok(()) } @@ -139,8 +137,8 @@ async fn vote_post( score: vote_type.into(), }; let person_id = actor.id; - PostLike::remove(context.conn().await?, person_id, post_id).await?; - PostLike::like(context.conn().await?, &like_form).await?; + PostLike::remove(context.pool(), person_id, post_id).await?; + PostLike::like(context.pool(), &like_form).await?; Ok(()) } @@ -152,7 +150,7 @@ async fn undo_vote_comment( ) -> Result<(), LemmyError> { let comment_id = comment.id; let person_id = actor.id; - CommentLike::remove(context.conn().await?, person_id, comment_id).await?; + CommentLike::remove(context.pool(), person_id, comment_id).await?; Ok(()) } @@ -164,6 +162,6 @@ async fn undo_vote_post( ) -> Result<(), LemmyError> { let post_id = post.id; let person_id = actor.id; - PostLike::remove(context.conn().await?, person_id, post_id).await?; + PostLike::remove(context.pool(), person_id, post_id).await?; Ok(()) } diff --git a/crates/apub/src/activities/voting/vote.rs b/crates/apub/src/activities/voting/vote.rs index 8b6ed2a9d..7f36ed471 100644 --- a/crates/apub/src/activities/voting/vote.rs +++ b/crates/apub/src/activities/voting/vote.rs @@ -58,7 +58,7 @@ impl ActivityHandler for Vote { async fn verify(&self, context: &Data) -> Result<(), LemmyError> { let community = self.community(context).await?; verify_person_in_community(&self.actor, &community, context).await?; - let enable_downvotes = LocalSite::read(context.conn().await?) + let enable_downvotes = LocalSite::read(context.pool()) .await .map(|l| l.enable_downvotes) .unwrap_or(true); diff --git a/crates/apub/src/api/list_comments.rs b/crates/apub/src/api/list_comments.rs index d4711c5b2..edb70dbaa 100644 --- a/crates/apub/src/api/list_comments.rs +++ b/crates/apub/src/api/list_comments.rs @@ -23,7 +23,7 @@ pub async fn list_comments( context: Data, ) -> Result, LemmyError> { let local_user_view = local_user_view_from_jwt_opt(data.auth.as_ref(), &context).await; - let local_site = LocalSite::read(context.conn().await?).await?; + let local_site = LocalSite::read(context.pool()).await?; check_private_instance(&local_user_view, &local_site)?; let community_id = if let Some(name) = &data.community_name { @@ -43,7 +43,7 @@ pub async fn list_comments( // If a parent_id is given, fetch the comment to get the path let parent_path = if let Some(parent_id) = parent_id { - Some(Comment::read(context.conn().await?, parent_id).await?.path) + Some(Comment::read(context.pool(), parent_id).await?.path) } else { None }; @@ -52,7 +52,7 @@ pub async fn list_comments( let post_id = data.post_id; let local_user = local_user_view.map(|l| l.local_user); let comments = CommentQuery::builder() - .conn(context.conn().await?) + .pool(context.pool()) .listing_type(Some(listing_type)) .sort(sort) .max_depth(max_depth) diff --git a/crates/apub/src/api/list_posts.rs b/crates/apub/src/api/list_posts.rs index 48bae8e85..ff7ac1089 100644 --- a/crates/apub/src/api/list_posts.rs +++ b/crates/apub/src/api/list_posts.rs @@ -20,7 +20,7 @@ pub async fn list_posts( context: Data, ) -> Result, LemmyError> { let local_user_view = local_user_view_from_jwt_opt(data.auth.as_ref(), &context).await; - let local_site = LocalSite::read(context.conn().await?).await?; + let local_site = LocalSite::read(context.pool()).await?; check_private_instance(&local_user_view, &local_site)?; @@ -38,16 +38,12 @@ pub async fn list_posts( let listing_type = listing_type_with_default(data.type_, &local_site, community_id)?; - let is_mod_or_admin = is_mod_or_admin_opt( - context.conn().await?, - local_user_view.as_ref(), - community_id, - ) - .await - .is_ok(); + let is_mod_or_admin = is_mod_or_admin_opt(context.pool(), local_user_view.as_ref(), community_id) + .await + .is_ok(); let posts = PostQuery::builder() - .conn(context.conn().await?) + .pool(context.pool()) .local_user(local_user_view.map(|l| l.local_user).as_ref()) .listing_type(Some(listing_type)) .sort(sort) diff --git a/crates/apub/src/api/read_community.rs b/crates/apub/src/api/read_community.rs index 922c35651..e524694d3 100644 --- a/crates/apub/src/api/read_community.rs +++ b/crates/apub/src/api/read_community.rs @@ -21,7 +21,7 @@ pub async fn read_community( context: Data, ) -> Result, LemmyError> { let local_user_view = local_user_view_from_jwt_opt(data.auth.as_ref(), &context).await; - let local_site = LocalSite::read(context.conn().await?).await?; + let local_site = LocalSite::read(context.pool()).await?; if data.name.is_none() && data.id.is_none() { return Err(LemmyError::from_message("no_id_given")); @@ -42,16 +42,13 @@ pub async fn read_community( } }; - let is_mod_or_admin = is_mod_or_admin_opt( - context.conn().await?, - local_user_view.as_ref(), - Some(community_id), - ) - .await - .is_ok(); + let is_mod_or_admin = + is_mod_or_admin_opt(context.pool(), local_user_view.as_ref(), Some(community_id)) + .await + .is_ok(); let community_view = CommunityView::read( - context.conn().await?, + context.pool(), community_id, person_id, Some(is_mod_or_admin), @@ -59,12 +56,12 @@ pub async fn read_community( .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?; - let moderators = CommunityModeratorView::for_community(context.conn().await?, community_id) + let moderators = CommunityModeratorView::for_community(context.pool(), community_id) .await .map_err(|e| LemmyError::from_error_message(e, "couldnt_find_community"))?; let site_id = Site::instance_actor_id_from_url(community_view.community.actor_id.clone().into()); - let mut site = Site::read_from_apub_id(context.conn().await?, &site_id.into()).await?; + let mut site = Site::read_from_apub_id(context.pool(), &site_id.into()).await?; // no need to include metadata for local site (its already available through other endpoints). // this also prevents us from leaking the federation private key. if let Some(s) = &site { @@ -74,7 +71,7 @@ pub async fn read_community( } let community_id = community_view.community.id; - let discussion_languages = CommunityLanguage::read(context.conn().await?, community_id).await?; + let discussion_languages = CommunityLanguage::read(context.pool(), community_id).await?; Ok(Json(GetCommunityResponse { community_view, diff --git a/crates/apub/src/api/read_person.rs b/crates/apub/src/api/read_person.rs index be16b5773..fb4755e38 100644 --- a/crates/apub/src/api/read_person.rs +++ b/crates/apub/src/api/read_person.rs @@ -25,7 +25,7 @@ pub async fn read_person( } let local_user_view = local_user_view_from_jwt_opt(data.auth.as_ref(), &context).await; - let local_site = LocalSite::read(context.conn().await?).await?; + let local_site = LocalSite::read(context.pool()).await?; let is_admin = local_user_view.as_ref().map(|luv| is_admin(luv).is_ok()); check_private_instance(&local_user_view, &local_site)?; @@ -48,7 +48,7 @@ pub async fn read_person( // You don't need to return settings for the user, since this comes back with GetSite // `my_user` - let person_view = PersonView::read(context.conn().await?, person_details_id).await?; + let person_view = PersonView::read(context.pool(), person_details_id).await?; let sort = data.sort; let page = data.page; @@ -59,7 +59,7 @@ pub async fn read_person( let local_user_clone = local_user.clone(); let posts_query = PostQuery::builder() - .conn(context.conn().await?) + .pool(context.pool()) .sort(sort) .saved_only(saved_only) .local_user(local_user.as_ref()) @@ -81,7 +81,7 @@ pub async fn read_person( .await?; let comments_query = CommentQuery::builder() - .conn(context.conn().await?) + .pool(context.pool()) .local_user(local_user_clone.as_ref()) .sort(sort.map(post_to_comment_sort_type)) .saved_only(saved_only) @@ -102,8 +102,7 @@ pub async fn read_person( } .await?; - let moderates = - CommunityModeratorView::for_person(context.conn().await?, person_details_id).await?; + let moderates = CommunityModeratorView::for_person(context.pool(), person_details_id).await?; // Return the jwt Ok(Json(GetPersonDetailsResponse { diff --git a/crates/apub/src/api/resolve_object.rs b/crates/apub/src/api/resolve_object.rs index d828b41fe..09689def1 100644 --- a/crates/apub/src/api/resolve_object.rs +++ b/crates/apub/src/api/resolve_object.rs @@ -7,7 +7,7 @@ use lemmy_api_common::{ site::{ResolveObject, ResolveObjectResponse}, utils::{check_private_instance, local_user_view_from_jwt}, }; -use lemmy_db_schema::{newtypes::PersonId, source::local_site::LocalSite, utils::GetConn}; +use lemmy_db_schema::{newtypes::PersonId, source::local_site::LocalSite, utils::DbPool}; use lemmy_db_views::structs::{CommentView, PostView}; use lemmy_db_views_actor::structs::{CommunityView, PersonView}; use lemmy_utils::error::LemmyError; @@ -18,14 +18,14 @@ pub async fn resolve_object( context: Data, ) -> Result, LemmyError> { let local_user_view = local_user_view_from_jwt(&data.auth, &context).await?; - let local_site = LocalSite::read(context.conn().await?).await?; + let local_site = LocalSite::read(context.pool()).await?; let person_id = local_user_view.person.id; check_private_instance(&Some(local_user_view), &local_site)?; let res = search_query_to_object_id(&data.q, &context) .await .map_err(|e| e.with_message("couldnt_find_object"))?; - convert_response(res, person_id, context.conn().await?) + convert_response(res, person_id, context.pool()) .await .map_err(|e| e.with_message("couldnt_find_object")) } @@ -33,7 +33,7 @@ pub async fn resolve_object( async fn convert_response( object: SearchableObjects, user_id: PersonId, - conn: impl GetConn, + pool: &DbPool, ) -> Result, LemmyError> { use SearchableObjects::*; let removed_or_deleted; @@ -41,19 +41,19 @@ async fn convert_response( match object { Person(p) => { removed_or_deleted = p.deleted; - res.person = Some(PersonView::read(conn, p.id).await?) + res.person = Some(PersonView::read(pool, p.id).await?) } Community(c) => { removed_or_deleted = c.deleted || c.removed; - res.community = Some(CommunityView::read(conn, c.id, Some(user_id), None).await?) + res.community = Some(CommunityView::read(pool, c.id, Some(user_id), None).await?) } Post(p) => { removed_or_deleted = p.deleted || p.removed; - res.post = Some(PostView::read(conn, p.id, Some(user_id), None).await?) + res.post = Some(PostView::read(pool, p.id, Some(user_id), None).await?) } Comment(c) => { removed_or_deleted = c.deleted || c.removed; - res.comment = Some(CommentView::read(conn, c.id, Some(user_id)).await?) + res.comment = Some(CommentView::read(pool, c.id, Some(user_id)).await?) } }; // if the object was deleted from database, dont return it diff --git a/crates/apub/src/api/search.rs b/crates/apub/src/api/search.rs index 177117d29..0f9a6b37f 100644 --- a/crates/apub/src/api/search.rs +++ b/crates/apub/src/api/search.rs @@ -21,7 +21,7 @@ pub async fn search( context: Data, ) -> Result, LemmyError> { let local_user_view = local_user_view_from_jwt_opt(data.auth.as_ref(), &context).await; - let local_site = LocalSite::read(context.conn().await?).await?; + let local_site = LocalSite::read(context.pool()).await?; check_private_instance(&local_user_view, &local_site)?; @@ -54,7 +54,7 @@ pub async fn search( match search_type { SearchType::Posts => { posts = PostQuery::builder() - .conn(context.conn().await?) + .pool(context.pool()) .sort(sort) .listing_type(listing_type) .community_id(community_id) @@ -70,7 +70,7 @@ pub async fn search( } SearchType::Comments => { comments = CommentQuery::builder() - .conn(context.conn().await?) + .pool(context.pool()) .sort(sort.map(post_to_comment_sort_type)) .listing_type(listing_type) .search_term(Some(q)) @@ -85,7 +85,7 @@ pub async fn search( } SearchType::Communities => { communities = CommunityQuery::builder() - .conn(context.conn().await?) + .pool(context.pool()) .sort(sort) .listing_type(listing_type) .search_term(Some(q)) @@ -99,7 +99,7 @@ pub async fn search( } SearchType::Users => { users = PersonQuery::builder() - .conn(context.conn().await?) + .pool(context.pool()) .sort(sort) .search_term(Some(q)) .page(page) @@ -115,7 +115,7 @@ pub async fn search( let local_user_ = local_user.clone(); posts = PostQuery::builder() - .conn(context.conn().await?) + .pool(context.pool()) .sort(sort) .listing_type(listing_type) .community_id(community_id) @@ -133,7 +133,7 @@ pub async fn search( let local_user_ = local_user.clone(); comments = CommentQuery::builder() - .conn(context.conn().await?) + .pool(context.pool()) .sort(sort.map(post_to_comment_sort_type)) .listing_type(listing_type) .search_term(Some(q)) @@ -152,7 +152,7 @@ pub async fn search( vec![] } else { CommunityQuery::builder() - .conn(context.conn().await?) + .pool(context.pool()) .sort(sort) .listing_type(listing_type) .search_term(Some(q)) @@ -171,7 +171,7 @@ pub async fn search( vec![] } else { PersonQuery::builder() - .conn(context.conn().await?) + .pool(context.pool()) .sort(sort) .search_term(Some(q)) .page(page) @@ -183,7 +183,7 @@ pub async fn search( } SearchType::Url => { posts = PostQuery::builder() - .conn(context.conn().await?) + .pool(context.pool()) .sort(sort) .listing_type(listing_type) .community_id(community_id) diff --git a/crates/apub/src/collections/community_featured.rs b/crates/apub/src/collections/community_featured.rs index 730e086fd..0743a9fbd 100644 --- a/crates/apub/src/collections/community_featured.rs +++ b/crates/apub/src/collections/community_featured.rs @@ -29,7 +29,7 @@ impl Collection for ApubCommunityFeatured { data: &Data, ) -> Result { let ordered_items = try_join_all( - Post::list_featured_for_community(data.conn().await?, owner.id) + Post::list_featured_for_community(data.pool(), owner.id) .await? .into_iter() .map(ApubPost::from) diff --git a/crates/apub/src/collections/community_moderators.rs b/crates/apub/src/collections/community_moderators.rs index 8b8946bff..d53f86280 100644 --- a/crates/apub/src/collections/community_moderators.rs +++ b/crates/apub/src/collections/community_moderators.rs @@ -33,7 +33,7 @@ impl Collection for ApubCommunityModerators { owner: &Self::Owner, data: &Data, ) -> Result { - let moderators = CommunityModeratorView::for_community(data.conn().await?, owner.id).await?; + let moderators = CommunityModeratorView::for_community(data.pool(), owner.id).await?; let ordered_items = moderators .into_iter() .map(|m| ObjectId::::from(m.moderator.actor_id)) @@ -63,7 +63,7 @@ impl Collection for ApubCommunityModerators { ) -> Result { let community_id = owner.id; let current_moderators = - CommunityModeratorView::for_community(data.conn().await?, community_id).await?; + CommunityModeratorView::for_community(data.pool(), community_id).await?; // Remove old mods from database which arent in the moderators collection anymore for mod_user in ¤t_moderators { let mod_id = ObjectId::from(mod_user.moderator.actor_id.clone()); @@ -72,7 +72,7 @@ impl Collection for ApubCommunityModerators { community_id: mod_user.community.id, person_id: mod_user.moderator.id, }; - CommunityModerator::leave(data.conn().await?, &community_moderator_form).await?; + CommunityModerator::leave(data.pool(), &community_moderator_form).await?; } } @@ -89,7 +89,7 @@ impl Collection for ApubCommunityModerators { community_id: owner.id, person_id: mod_user.id, }; - CommunityModerator::join(data.conn().await?, &community_moderator_form).await?; + CommunityModerator::join(data.pool(), &community_moderator_form).await?; } } @@ -128,10 +128,9 @@ mod tests { let community = parse_lemmy_community(&context).await; let community_id = community.id; - let inserted_instance = - Instance::read_or_create(context.conn().await.unwrap(), "my_domain.tld".to_string()) - .await - .unwrap(); + let inserted_instance = Instance::read_or_create(context.pool(), "my_domain.tld".to_string()) + .await + .unwrap(); let old_mod = PersonInsertForm::builder() .name("holly".into()) @@ -139,15 +138,13 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let old_mod = Person::create(context.conn().await.unwrap(), &old_mod) - .await - .unwrap(); + let old_mod = Person::create(context.pool(), &old_mod).await.unwrap(); let community_moderator_form = CommunityModeratorForm { community_id: community.id, person_id: old_mod.id, }; - CommunityModerator::join(context.conn().await.unwrap(), &community_moderator_form) + CommunityModerator::join(context.pool(), &community_moderator_form) .await .unwrap(); @@ -164,27 +161,20 @@ mod tests { .unwrap(); assert_eq!(context.request_count(), 0); - let current_moderators = - CommunityModeratorView::for_community(context.conn().await.unwrap(), community_id) - .await - .unwrap(); + let current_moderators = CommunityModeratorView::for_community(context.pool(), community_id) + .await + .unwrap(); assert_eq!(current_moderators.len(), 1); assert_eq!(current_moderators[0].moderator.id, new_mod.id); - Person::delete(context.conn().await.unwrap(), old_mod.id) + Person::delete(context.pool(), old_mod.id).await.unwrap(); + Person::delete(context.pool(), new_mod.id).await.unwrap(); + Community::delete(context.pool(), community.id) .await .unwrap(); - Person::delete(context.conn().await.unwrap(), new_mod.id) - .await - .unwrap(); - Community::delete(context.conn().await.unwrap(), community.id) - .await - .unwrap(); - Site::delete(context.conn().await.unwrap(), site.id) - .await - .unwrap(); - Instance::delete(context.conn().await.unwrap(), inserted_instance.id) + Site::delete(context.pool(), site.id).await.unwrap(); + Instance::delete(context.pool(), inserted_instance.id) .await .unwrap(); } diff --git a/crates/apub/src/collections/community_outbox.rs b/crates/apub/src/collections/community_outbox.rs index 550d7dbee..c95b64aab 100644 --- a/crates/apub/src/collections/community_outbox.rs +++ b/crates/apub/src/collections/community_outbox.rs @@ -41,16 +41,14 @@ impl Collection for ApubCommunityOutbox { owner: &Self::Owner, data: &Data, ) -> Result { - let post_list: Vec = Post::list_for_community(data.conn().await?, owner.id) + let post_list: Vec = Post::list_for_community(data.pool(), owner.id) .await? .into_iter() .map(Into::into) .collect(); let mut ordered_items = vec![]; for post in post_list { - let person = Person::read(data.conn().await?, post.creator_id) - .await? - .into(); + let person = Person::read(data.pool(), post.creator_id).await?.into(); let create = CreateOrUpdatePage::new(post, &person, owner, CreateOrUpdateType::Create, data).await?; let announcable = AnnouncableActivities::CreateOrUpdatePost(create); diff --git a/crates/apub/src/fetcher/mod.rs b/crates/apub/src/fetcher/mod.rs index a20e52cd0..4f72d1488 100644 --- a/crates/apub/src/fetcher/mod.rs +++ b/crates/apub/src/fetcher/mod.rs @@ -41,7 +41,7 @@ where .splitn(2, '@') .collect_tuple() .expect("invalid query"); - let actor = DbActor::read_from_name_and_domain(context.conn().await?, name, domain).await; + let actor = DbActor::read_from_name_and_domain(context.pool(), name, domain).await; if actor.is_ok() { Ok(actor?.into()) } else if local_user_view.is_some() { @@ -56,7 +56,7 @@ where else { let identifier = identifier.to_string(); Ok( - DbActor::read_from_name(context.conn().await?, &identifier, include_deleted) + DbActor::read_from_name(context.pool(), &identifier, include_deleted) .await? .into(), ) diff --git a/crates/apub/src/fetcher/post_or_comment.rs b/crates/apub/src/fetcher/post_or_comment.rs index 613270472..651abf7db 100644 --- a/crates/apub/src/fetcher/post_or_comment.rs +++ b/crates/apub/src/fetcher/post_or_comment.rs @@ -91,12 +91,8 @@ impl InCommunity for PostOrComment { async fn community(&self, context: &Data) -> Result { let cid = match self { PostOrComment::Post(p) => p.community_id, - PostOrComment::Comment(c) => { - Post::read(context.conn().await?, c.post_id) - .await? - .community_id - } + PostOrComment::Comment(c) => Post::read(context.pool(), c.post_id).await?.community_id, }; - Ok(Community::read(context.conn().await?, cid).await?.into()) + Ok(Community::read(context.pool(), cid).await?.into()) } } diff --git a/crates/apub/src/http/comment.rs b/crates/apub/src/http/comment.rs index bb8be331a..9e78da2ab 100644 --- a/crates/apub/src/http/comment.rs +++ b/crates/apub/src/http/comment.rs @@ -21,7 +21,7 @@ pub(crate) async fn get_apub_comment( context: Data, ) -> Result { let id = CommentId(info.comment_id.parse::()?); - let comment: ApubComment = Comment::read(context.conn().await?, id).await?.into(); + let comment: ApubComment = Comment::read(context.pool(), id).await?.into(); if !comment.local { return Err(err_object_not_local()); } diff --git a/crates/apub/src/http/community.rs b/crates/apub/src/http/community.rs index 38a9080a7..04ac8e3fd 100644 --- a/crates/apub/src/http/community.rs +++ b/crates/apub/src/http/community.rs @@ -33,7 +33,7 @@ pub(crate) async fn get_apub_community_http( context: Data, ) -> Result { let community: ApubCommunity = - Community::read_from_name(context.conn().await?, &info.community_name, true) + Community::read_from_name(context.pool(), &info.community_name, true) .await? .into(); @@ -64,8 +64,7 @@ pub(crate) async fn get_apub_community_followers( info: web::Path, context: Data, ) -> Result { - let community = - Community::read_from_name(context.conn().await?, &info.community_name, false).await?; + let community = Community::read_from_name(context.pool(), &info.community_name, false).await?; let followers = GroupFollowers::new(community, &context).await?; create_apub_response(&followers) } @@ -77,7 +76,7 @@ pub(crate) async fn get_apub_community_outbox( context: Data, ) -> Result { let community: ApubCommunity = - Community::read_from_name(context.conn().await?, &info.community_name, false) + Community::read_from_name(context.pool(), &info.community_name, false) .await? .into(); if community.deleted || community.removed { @@ -93,7 +92,7 @@ pub(crate) async fn get_apub_community_moderators( context: Data, ) -> Result { let community: ApubCommunity = - Community::read_from_name(context.conn().await?, &info.community_name, false) + Community::read_from_name(context.pool(), &info.community_name, false) .await? .into(); if community.deleted || community.removed { @@ -109,7 +108,7 @@ pub(crate) async fn get_apub_community_featured( context: Data, ) -> Result { let community: ApubCommunity = - Community::read_from_name(context.conn().await?, &info.community_name, false) + Community::read_from_name(context.pool(), &info.community_name, false) .await? .into(); if community.deleted || community.removed { diff --git a/crates/apub/src/http/mod.rs b/crates/apub/src/http/mod.rs index 74cc9a0f2..66d5a0f9f 100644 --- a/crates/apub/src/http/mod.rs +++ b/crates/apub/src/http/mod.rs @@ -88,7 +88,7 @@ pub(crate) async fn get_activity( info.id ))? .into(); - let activity = Activity::read_from_apub_id(context.conn().await?, &activity_id).await?; + let activity = Activity::read_from_apub_id(context.pool(), &activity_id).await?; let sensitive = activity.sensitive; if !activity.local { diff --git a/crates/apub/src/http/person.rs b/crates/apub/src/http/person.rs index d581ceb61..453905eee 100644 --- a/crates/apub/src/http/person.rs +++ b/crates/apub/src/http/person.rs @@ -30,7 +30,7 @@ pub(crate) async fn get_apub_person_http( ) -> Result { let user_name = info.into_inner().user_name; // TODO: this needs to be able to read deleted persons, so that it can send tombstones - let person: ApubPerson = Person::read_from_name(context.conn().await?, &user_name, true) + let person: ApubPerson = Person::read_from_name(context.pool(), &user_name, true) .await? .into(); @@ -60,7 +60,7 @@ pub(crate) async fn get_apub_person_outbox( info: web::Path, context: Data, ) -> Result { - let person = Person::read_from_name(context.conn().await?, &info.user_name, false).await?; + let person = Person::read_from_name(context.pool(), &info.user_name, false).await?; let outbox_id = generate_outbox_url(&person.actor_id)?.into(); let outbox = EmptyOutbox::new(outbox_id)?; create_apub_response(&outbox) diff --git a/crates/apub/src/http/post.rs b/crates/apub/src/http/post.rs index 4398ac7f6..a2e600268 100644 --- a/crates/apub/src/http/post.rs +++ b/crates/apub/src/http/post.rs @@ -21,7 +21,7 @@ pub(crate) async fn get_apub_post( context: Data, ) -> Result { let id = PostId(info.post_id.parse::()?); - let post: ApubPost = Post::read(context.conn().await?, id).await?.into(); + let post: ApubPost = Post::read(context.pool(), id).await?.into(); if !post.local { return Err(err_object_not_local()); } diff --git a/crates/apub/src/http/site.rs b/crates/apub/src/http/site.rs index bf680bff8..676ce9bd6 100644 --- a/crates/apub/src/http/site.rs +++ b/crates/apub/src/http/site.rs @@ -19,10 +19,7 @@ use url::Url; pub(crate) async fn get_apub_site_http( context: Data, ) -> Result { - let site: ApubSite = SiteView::read_local(context.conn().await?) - .await? - .site - .into(); + let site: ApubSite = SiteView::read_local(context.pool()).await?.site.into(); let apub = site.into_json(&context).await?; create_apub_response(&apub) diff --git a/crates/apub/src/lib.rs b/crates/apub/src/lib.rs index 0252e0aa0..a5bc41d1f 100644 --- a/crates/apub/src/lib.rs +++ b/crates/apub/src/lib.rs @@ -9,7 +9,7 @@ use lemmy_db_schema::{ local_site::LocalSite, }, traits::Crud, - utils::{get_conn, DbPool}, + utils::DbPool, }; use lemmy_utils::{error::LemmyError, settings::structs::Settings}; use once_cell::sync::Lazy; @@ -101,9 +101,9 @@ pub(crate) async fn fetch_local_site_data( pool: &DbPool, ) -> Result { // LocalSite may be missing - let local_site = LocalSite::read(get_conn(pool).await?).await.ok(); - let allowed_instances = Instance::allowlist(get_conn(pool).await?).await?; - let blocked_instances = Instance::blocklist(get_conn(pool).await?).await?; + let local_site = LocalSite::read(pool).await.ok(); + let allowed_instances = Instance::allowlist(pool).await?; + let blocked_instances = Instance::blocklist(pool).await?; Ok(LocalSiteData { local_site, @@ -175,7 +175,7 @@ where sensitive: Some(sensitive), updated: None, }; - Activity::create(data.conn().await?, &form).await?; + Activity::create(data.pool(), &form).await?; Ok(()) } diff --git a/crates/apub/src/mentions.rs b/crates/apub/src/mentions.rs index 45e094fae..088f84d0d 100644 --- a/crates/apub/src/mentions.rs +++ b/crates/apub/src/mentions.rs @@ -9,7 +9,7 @@ use lemmy_api_common::context::LemmyContext; use lemmy_db_schema::{ source::{comment::Comment, person::Person, post::Post}, traits::Crud, - utils::{get_conn, DbPool}, + utils::DbPool, }; use lemmy_utils::{error::LemmyError, utils::mention::scrape_text_for_mentions}; use serde::{Deserialize, Serialize}; @@ -96,16 +96,12 @@ async fn get_comment_parent_creator( comment: &Comment, ) -> Result { let parent_creator_id = if let Some(parent_comment_id) = comment.parent_comment_id() { - let parent_comment = Comment::read(get_conn(pool).await?, parent_comment_id).await?; + let parent_comment = Comment::read(pool, parent_comment_id).await?; parent_comment.creator_id } else { let parent_post_id = comment.post_id; - let parent_post = Post::read(get_conn(pool).await?, parent_post_id).await?; + let parent_post = Post::read(pool, parent_post_id).await?; parent_post.creator_id }; - Ok( - Person::read(get_conn(pool).await?, parent_creator_id) - .await? - .into(), - ) + Ok(Person::read(pool, parent_creator_id).await?.into()) } diff --git a/crates/apub/src/objects/comment.rs b/crates/apub/src/objects/comment.rs index 65354c345..16cb1542b 100644 --- a/crates/apub/src/objects/comment.rs +++ b/crates/apub/src/objects/comment.rs @@ -67,7 +67,7 @@ impl Object for ApubComment { context: &Data, ) -> Result, LemmyError> { Ok( - Comment::read_from_apub_id(context.conn().await?, object_id) + Comment::read_from_apub_id(context.pool(), object_id) .await? .map(Into::into), ) @@ -77,7 +77,7 @@ impl Object for ApubComment { async fn delete(self, context: &Data) -> Result<(), LemmyError> { if !self.deleted { let form = CommentUpdateForm::builder().deleted(Some(true)).build(); - Comment::update(context.conn().await?, self.id, &form).await?; + Comment::update(context.pool(), self.id, &form).await?; } Ok(()) } @@ -85,20 +85,20 @@ impl Object for ApubComment { #[tracing::instrument(skip_all)] async fn into_json(self, context: &Data) -> Result { let creator_id = self.creator_id; - let creator = Person::read(context.conn().await?, creator_id).await?; + let creator = Person::read(context.pool(), creator_id).await?; let post_id = self.post_id; - let post = Post::read(context.conn().await?, post_id).await?; + let post = Post::read(context.pool(), post_id).await?; let community_id = post.community_id; - let community = Community::read(context.conn().await?, community_id).await?; + let community = Community::read(context.pool(), community_id).await?; let in_reply_to = if let Some(comment_id) = self.parent_comment_id() { - let parent_comment = Comment::read(context.conn().await?, comment_id).await?; + let parent_comment = Comment::read(context.pool(), comment_id).await?; parent_comment.ap_id.into() } else { post.ap_id.into() }; - let language = LanguageTag::new_single(self.language_id, context.conn().await?).await?; + let language = LanguageTag::new_single(self.language_id, context.pool()).await?; let maa = collect_non_local_mentions(&self, community.actor_id.clone().into(), context).await?; let note = Note { @@ -159,11 +159,10 @@ impl Object for ApubComment { let content = read_from_string_or_source(¬e.content, ¬e.media_type, ¬e.source); - let local_site = LocalSite::read(context.conn().await?).await.ok(); + let local_site = LocalSite::read(context.pool()).await.ok(); let slur_regex = &local_site_opt_to_slur_regex(&local_site); let content_slurs_removed = remove_slurs(&content, slur_regex); - let language_id = - LanguageTag::to_language_id_single(note.language, context.conn().await?).await?; + let language_id = LanguageTag::to_language_id_single(note.language, context.pool()).await?; let form = CommentInsertForm { creator_id: creator.id, @@ -179,8 +178,7 @@ impl Object for ApubComment { language_id, }; let parent_comment_path = parent_comment.map(|t| t.0.path); - let comment = - Comment::create(context.conn().await?, &form, parent_comment_path.as_ref()).await?; + let comment = Comment::create(context.pool(), &form, parent_comment_path.as_ref()).await?; Ok(comment.into()) } } @@ -218,21 +216,11 @@ pub(crate) mod tests { } async fn cleanup(data: (ApubPerson, ApubCommunity, ApubPost, ApubSite), context: &LemmyContext) { - Post::delete(context.conn().await.unwrap(), data.2.id) - .await - .unwrap(); - Community::delete(context.conn().await.unwrap(), data.1.id) - .await - .unwrap(); - Person::delete(context.conn().await.unwrap(), data.0.id) - .await - .unwrap(); - Site::delete(context.conn().await.unwrap(), data.3.id) - .await - .unwrap(); - LocalSite::delete(context.conn().await.unwrap()) - .await - .unwrap(); + Post::delete(context.pool(), data.2.id).await.unwrap(); + Community::delete(context.pool(), data.1.id).await.unwrap(); + Person::delete(context.pool(), data.0.id).await.unwrap(); + Site::delete(context.pool(), data.3.id).await.unwrap(); + LocalSite::delete(context.pool()).await.unwrap(); } #[tokio::test] @@ -257,9 +245,7 @@ pub(crate) mod tests { let to_apub = comment.into_json(&context).await.unwrap(); assert_json_include!(actual: json, expected: to_apub); - Comment::delete(context.conn().await.unwrap(), comment_id) - .await - .unwrap(); + Comment::delete(context.pool(), comment_id).await.unwrap(); cleanup(data, &context).await; } @@ -289,9 +275,7 @@ pub(crate) mod tests { assert!(!comment.local); assert_eq!(context.request_count(), 1); - Comment::delete(context.conn().await.unwrap(), comment.id) - .await - .unwrap(); + Comment::delete(context.pool(), comment.id).await.unwrap(); cleanup(data, &context).await; } diff --git a/crates/apub/src/objects/community.rs b/crates/apub/src/objects/community.rs index 408596814..17476e9f8 100644 --- a/crates/apub/src/objects/community.rs +++ b/crates/apub/src/objects/community.rs @@ -67,7 +67,7 @@ impl Object for ApubCommunity { context: &Data, ) -> Result, LemmyError> { Ok( - Community::read_from_apub_id(context.conn().await?, &object_id.into()) + Community::read_from_apub_id(context.pool(), &object_id.into()) .await? .map(Into::into), ) @@ -76,15 +76,15 @@ impl Object for ApubCommunity { #[tracing::instrument(skip_all)] async fn delete(self, context: &Data) -> Result<(), LemmyError> { let form = CommunityUpdateForm::builder().deleted(Some(true)).build(); - Community::update(context.conn().await?, self.id, &form).await?; + Community::update(context.pool(), self.id, &form).await?; Ok(()) } #[tracing::instrument(skip_all)] async fn into_json(self, data: &Data) -> Result { let community_id = self.id; - let langs = CommunityLanguage::read(data.conn().await?, community_id).await?; - let language = LanguageTag::new_multiple(langs, data.conn().await?).await?; + let langs = CommunityLanguage::read(data.pool(), community_id).await?; + let language = LanguageTag::new_multiple(langs, data.pool()).await?; let group = Group { kind: GroupType::Group, @@ -131,11 +131,10 @@ impl Object for ApubCommunity { let instance_id = fetch_instance_actor_for_object(&group.id, context).await?; let form = Group::into_insert_form(group.clone(), instance_id); - let languages = - LanguageTag::to_language_id_multiple(group.language, context.conn().await?).await?; + let languages = LanguageTag::to_language_id_multiple(group.language, context.pool()).await?; - let community = Community::create(context.conn().await?, &form).await?; - CommunityLanguage::update(context.conn().await?, languages, community.id).await?; + let community = Community::create(context.pool(), &form).await?; + CommunityLanguage::update(context.pool(), languages, community.id).await?; let community: ApubCommunity = community.into(); @@ -189,7 +188,7 @@ impl ApubCommunity { let id = self.id; let local_site_data = fetch_local_site_data(context.pool()).await?; - let follows = CommunityFollowerView::for_community(context.conn().await?, id).await?; + let follows = CommunityFollowerView::for_community(context.pool(), id).await?; let inboxes: Vec = follows .into_iter() .filter(|f| !f.follower.local) @@ -251,11 +250,9 @@ pub(crate) mod tests { assert!(!community.local); assert_eq!(community.description.as_ref().unwrap().len(), 132); - Community::delete(context.conn().await.unwrap(), community.id) - .await - .unwrap(); - Site::delete(context.conn().await.unwrap(), site.id) + Community::delete(context.pool(), community.id) .await .unwrap(); + Site::delete(context.pool(), site.id).await.unwrap(); } } diff --git a/crates/apub/src/objects/instance.rs b/crates/apub/src/objects/instance.rs index fcdec1410..6cd27fbbd 100644 --- a/crates/apub/src/objects/instance.rs +++ b/crates/apub/src/objects/instance.rs @@ -25,7 +25,7 @@ use lemmy_db_schema::{ site::{Site, SiteInsertForm}, }, traits::Crud, - utils::{naive_now, GetConn}, + utils::{naive_now, DbPool}, }; use lemmy_utils::{ error::LemmyError, @@ -71,7 +71,7 @@ impl Object for ApubSite { data: &Data, ) -> Result, LemmyError> { Ok( - Site::read_from_apub_id(data.conn().await?, &object_id.into()) + Site::read_from_apub_id(data.pool(), &object_id.into()) .await? .map(Into::into), ) @@ -84,8 +84,8 @@ impl Object for ApubSite { #[tracing::instrument(skip_all)] async fn into_json(self, data: &Data) -> Result { let site_id = self.id; - let langs = SiteLanguage::read(data.conn().await?, site_id).await?; - let language = LanguageTag::new_multiple(langs, data.conn().await?).await?; + let langs = SiteLanguage::read(data.pool(), site_id).await?; + let language = LanguageTag::new_multiple(langs, data.pool()).await?; let instance = Instance { kind: ApplicationType::Application, @@ -128,7 +128,7 @@ impl Object for ApubSite { #[tracing::instrument(skip_all)] async fn from_json(apub: Self::Kind, data: &Data) -> Result { let domain = apub.id.inner().domain().expect("group id has domain"); - let instance = DbInstance::read_or_create(data.conn().await?, domain.to_string()).await?; + let instance = DbInstance::read_or_create(data.pool(), domain.to_string()).await?; let site_form = SiteInsertForm { name: apub.name.clone(), @@ -144,10 +144,10 @@ impl Object for ApubSite { private_key: None, instance_id: instance.id, }; - let languages = LanguageTag::to_language_id_multiple(apub.language, data.conn().await?).await?; + let languages = LanguageTag::to_language_id_multiple(apub.language, data.pool()).await?; - let site = Site::create(data.conn().await?, &site_form).await?; - SiteLanguage::update(data.conn().await?, languages, &site).await?; + let site = Site::create(data.pool(), &site_form).await?; + SiteLanguage::update(data.pool(), languages, &site).await?; Ok(site.into()) } } @@ -187,7 +187,7 @@ pub(in crate::objects) async fn fetch_instance_actor_for_object + C debug!("Failed to dereference site for {}: {}", &instance_id, e); let domain = instance_id.domain().expect("has domain"); Ok( - DbInstance::read_or_create(context.conn().await?, domain.to_string()) + DbInstance::read_or_create(context.pool(), domain.to_string()) .await? .id, ) @@ -195,11 +195,9 @@ pub(in crate::objects) async fn fetch_instance_actor_for_object + C } } -pub(crate) async fn remote_instance_inboxes( - mut conn: impl GetConn, -) -> Result, LemmyError> { +pub(crate) async fn remote_instance_inboxes(pool: &DbPool) -> Result, LemmyError> { Ok( - Site::read_remote_sites(conn) + Site::read_remote_sites(pool) .await? .into_iter() .map(|s| ApubSite::from(s).shared_inbox_or_inbox()) @@ -232,8 +230,6 @@ pub(crate) mod tests { assert_eq!(site.name, "Enterprise"); assert_eq!(site.description.as_ref().unwrap().len(), 15); - Site::delete(context.conn().await.unwrap(), site.id) - .await - .unwrap(); + Site::delete(context.pool(), site.id).await.unwrap(); } } diff --git a/crates/apub/src/objects/person.rs b/crates/apub/src/objects/person.rs index 78d9b9acb..3eeb733fd 100644 --- a/crates/apub/src/objects/person.rs +++ b/crates/apub/src/objects/person.rs @@ -69,7 +69,7 @@ impl Object for ApubPerson { context: &Data, ) -> Result, LemmyError> { Ok( - DbPerson::read_from_apub_id(context.conn().await?, &object_id.into()) + DbPerson::read_from_apub_id(context.pool(), &object_id.into()) .await? .map(Into::into), ) @@ -78,7 +78,7 @@ impl Object for ApubPerson { #[tracing::instrument(skip_all)] async fn delete(self, context: &Data) -> Result<(), LemmyError> { let form = PersonUpdateForm::builder().deleted(Some(true)).build(); - DbPerson::update(context.conn().await?, self.id, &form).await?; + DbPerson::update(context.pool(), self.id, &form).await?; Ok(()) } @@ -171,7 +171,7 @@ impl Object for ApubPerson { matrix_user_id: person.matrix_user_id, instance_id, }; - let person = DbPerson::upsert(context.conn().await?, &person_form).await?; + let person = DbPerson::upsert(context.pool(), &person_form).await?; Ok(person.into()) } @@ -262,11 +262,7 @@ pub(crate) mod tests { } async fn cleanup(data: (ApubPerson, ApubSite), context: &LemmyContext) { - DbPerson::delete(context.conn().await.unwrap(), data.0.id) - .await - .unwrap(); - Site::delete(context.conn().await.unwrap(), data.1.id) - .await - .unwrap(); + DbPerson::delete(context.pool(), data.0.id).await.unwrap(); + Site::delete(context.pool(), data.1.id).await.unwrap(); } } diff --git a/crates/apub/src/objects/post.rs b/crates/apub/src/objects/post.rs index 87786a8de..7878fcf12 100644 --- a/crates/apub/src/objects/post.rs +++ b/crates/apub/src/objects/post.rs @@ -83,7 +83,7 @@ impl Object for ApubPost { context: &Data, ) -> Result, LemmyError> { Ok( - Post::read_from_apub_id(context.conn().await?, object_id) + Post::read_from_apub_id(context.pool(), object_id) .await? .map(Into::into), ) @@ -93,7 +93,7 @@ impl Object for ApubPost { async fn delete(self, context: &Data) -> Result<(), LemmyError> { if !self.deleted { let form = PostUpdateForm::builder().deleted(Some(true)).build(); - Post::update(context.conn().await?, self.id, &form).await?; + Post::update(context.pool(), self.id, &form).await?; } Ok(()) } @@ -102,10 +102,10 @@ impl Object for ApubPost { #[tracing::instrument(skip_all)] async fn into_json(self, context: &Data) -> Result { let creator_id = self.creator_id; - let creator = Person::read(context.conn().await?, creator_id).await?; + let creator = Person::read(context.pool(), creator_id).await?; let community_id = self.community_id; - let community = Community::read(context.conn().await?, community_id).await?; - let language = LanguageTag::new_single(self.language_id, context.conn().await?).await?; + let community = Community::read(context.pool(), community_id).await?; + let language = LanguageTag::new_single(self.language_id, context.pool()).await?; let page = Page { kind: PageType::Page, @@ -167,7 +167,7 @@ impl Object for ApubPost { let creator = page.creator()?.dereference(context).await?; let community = page.community(context).await?; if community.posting_restricted_to_mods { - is_mod_or_admin(context.conn().await?, creator.id, community.id).await?; + is_mod_or_admin(context.pool(), creator.id, community.id).await?; } let mut name = page .name @@ -198,7 +198,7 @@ impl Object for ApubPost { None }; - let local_site = LocalSite::read(context.conn().await?).await.ok(); + let local_site = LocalSite::read(context.pool()).await.ok(); let allow_sensitive = local_site_opt_to_sensitive(&local_site); let page_is_sensitive = page.sensitive.unwrap_or(false); let include_image = allow_sensitive || !page_is_sensitive; @@ -229,8 +229,7 @@ impl Object for ApubPost { let body_slurs_removed = read_from_string_or_source_opt(&page.content, &page.media_type, &page.source) .map(|s| remove_slurs(&s, slur_regex)); - let language_id = - LanguageTag::to_language_id_single(page.language, context.conn().await?).await?; + let language_id = LanguageTag::to_language_id_single(page.language, context.pool()).await?; PostInsertForm { name, @@ -266,7 +265,7 @@ impl Object for ApubPost { .build() }; - let post = Post::create(context.conn().await?, &form).await?; + let post = Post::create(context.pool(), &form).await?; // write mod log entry for lock if Page::is_locked_changed(&old_post, &page.comments_enabled) { @@ -275,7 +274,7 @@ impl Object for ApubPost { post_id: post.id, locked: Some(post.locked), }; - ModLockPost::create(context.conn().await?, &form).await?; + ModLockPost::create(context.pool(), &form).await?; } Ok(post.into()) @@ -317,17 +316,11 @@ mod tests { assert!(!post.featured_community); assert_eq!(context.request_count(), 0); - Post::delete(context.conn().await.unwrap(), post.id) - .await - .unwrap(); - Person::delete(context.conn().await.unwrap(), person.id) - .await - .unwrap(); - Community::delete(context.conn().await.unwrap(), community.id) - .await - .unwrap(); - Site::delete(context.conn().await.unwrap(), site.id) + Post::delete(context.pool(), post.id).await.unwrap(); + Person::delete(context.pool(), person.id).await.unwrap(); + Community::delete(context.pool(), community.id) .await .unwrap(); + Site::delete(context.pool(), site.id).await.unwrap(); } } diff --git a/crates/apub/src/objects/private_message.rs b/crates/apub/src/objects/private_message.rs index c10d7b8c5..ae2637c58 100644 --- a/crates/apub/src/objects/private_message.rs +++ b/crates/apub/src/objects/private_message.rs @@ -60,7 +60,7 @@ impl Object for ApubPrivateMessage { context: &Data, ) -> Result, LemmyError> { Ok( - PrivateMessage::read_from_apub_id(context.conn().await?, object_id) + PrivateMessage::read_from_apub_id(context.pool(), object_id) .await? .map(Into::into), ) @@ -74,10 +74,10 @@ impl Object for ApubPrivateMessage { #[tracing::instrument(skip_all)] async fn into_json(self, context: &Data) -> Result { let creator_id = self.creator_id; - let creator = Person::read(context.conn().await?, creator_id).await?; + let creator = Person::read(context.pool(), creator_id).await?; let recipient_id = self.recipient_id; - let recipient = Person::read(context.conn().await?, recipient_id).await?; + let recipient = Person::read(context.pool(), recipient_id).await?; let note = ChatMessage { r#type: ChatMessageType::ChatMessage, @@ -124,7 +124,7 @@ impl Object for ApubPrivateMessage { ) -> Result { let creator = note.attributed_to.dereference(context).await?; let recipient = note.to[0].dereference(context).await?; - check_person_block(creator.id, recipient.id, context.conn().await?).await?; + check_person_block(creator.id, recipient.id, context.pool()).await?; let form = PrivateMessageInsertForm { creator_id: creator.id, @@ -137,7 +137,7 @@ impl Object for ApubPrivateMessage { ap_id: Some(note.id.into()), local: Some(false), }; - let pm = PrivateMessage::create(context.conn().await?, &form).await?; + let pm = PrivateMessage::create(context.pool(), &form).await?; Ok(pm.into()) } } @@ -182,15 +182,9 @@ mod tests { } async fn cleanup(data: (ApubPerson, ApubPerson, ApubSite), context: &Data) { - Person::delete(context.conn().await.unwrap(), data.0.id) - .await - .unwrap(); - Person::delete(context.conn().await.unwrap(), data.1.id) - .await - .unwrap(); - Site::delete(context.conn().await.unwrap(), data.2.id) - .await - .unwrap(); + Person::delete(context.pool(), data.0.id).await.unwrap(); + Person::delete(context.pool(), data.1.id).await.unwrap(); + Site::delete(context.pool(), data.2.id).await.unwrap(); } #[tokio::test] @@ -215,9 +209,7 @@ mod tests { let to_apub = pm.into_json(&context).await.unwrap(); assert_json_include!(actual: json, expected: to_apub); - PrivateMessage::delete(context.conn().await.unwrap(), pm_id) - .await - .unwrap(); + PrivateMessage::delete(context.pool(), pm_id).await.unwrap(); cleanup(data, &context).await; } @@ -238,9 +230,7 @@ mod tests { assert_eq!(pm.content.len(), 3); assert_eq!(context.request_count(), 0); - PrivateMessage::delete(context.conn().await.unwrap(), pm.id) - .await - .unwrap(); + PrivateMessage::delete(context.pool(), pm.id).await.unwrap(); cleanup(data, &context).await; } } diff --git a/crates/apub/src/protocol/activities/community/collection_add.rs b/crates/apub/src/protocol/activities/community/collection_add.rs index b32dc577d..f3943e31c 100644 --- a/crates/apub/src/protocol/activities/community/collection_add.rs +++ b/crates/apub/src/protocol/activities/community/collection_add.rs @@ -35,7 +35,7 @@ pub struct CollectionAdd { impl InCommunity for CollectionAdd { async fn community(&self, context: &Data) -> Result { let (community, _) = - Community::get_by_collection_url(context.conn().await?, &self.clone().target.into()).await?; + Community::get_by_collection_url(context.pool(), &self.clone().target.into()).await?; if let Some(audience) = &self.audience { verify_community_matches(audience, community.actor_id.clone())?; } diff --git a/crates/apub/src/protocol/activities/community/collection_remove.rs b/crates/apub/src/protocol/activities/community/collection_remove.rs index 3561db3f2..f69fdc6a7 100644 --- a/crates/apub/src/protocol/activities/community/collection_remove.rs +++ b/crates/apub/src/protocol/activities/community/collection_remove.rs @@ -35,7 +35,7 @@ pub struct CollectionRemove { impl InCommunity for CollectionRemove { async fn community(&self, context: &Data) -> Result { let (community, _) = - Community::get_by_collection_url(context.conn().await?, &self.clone().target.into()).await?; + Community::get_by_collection_url(context.pool(), &self.clone().target.into()).await?; if let Some(audience) = &self.audience { verify_community_matches(audience, community.actor_id.clone())?; } diff --git a/crates/apub/src/protocol/activities/community/lock_page.rs b/crates/apub/src/protocol/activities/community/lock_page.rs index 12882646c..b19e39749 100644 --- a/crates/apub/src/protocol/activities/community/lock_page.rs +++ b/crates/apub/src/protocol/activities/community/lock_page.rs @@ -55,7 +55,7 @@ pub struct UndoLockPage { impl InCommunity for LockPage { async fn community(&self, context: &Data) -> Result { let post = self.object.dereference(context).await?; - let community = Community::read(context.conn().await?, post.community_id).await?; + let community = Community::read(context.pool(), post.community_id).await?; if let Some(audience) = &self.audience { verify_community_matches(audience, community.actor_id.clone())?; } diff --git a/crates/apub/src/protocol/activities/create_or_update/note.rs b/crates/apub/src/protocol/activities/create_or_update/note.rs index 82fee38af..07bbc7c8d 100644 --- a/crates/apub/src/protocol/activities/create_or_update/note.rs +++ b/crates/apub/src/protocol/activities/create_or_update/note.rs @@ -36,7 +36,7 @@ pub struct CreateOrUpdateNote { impl InCommunity for CreateOrUpdateNote { async fn community(&self, context: &Data) -> Result { let post = self.object.get_parents(context).await?.0; - let community = Community::read(context.conn().await?, post.community_id).await?; + let community = Community::read(context.pool(), post.community_id).await?; if let Some(audience) = &self.audience { verify_community_matches(audience, community.actor_id.clone())?; } diff --git a/crates/apub/src/protocol/activities/deletion/delete.rs b/crates/apub/src/protocol/activities/deletion/delete.rs index 3ffb158d5..89ee26d94 100644 --- a/crates/apub/src/protocol/activities/deletion/delete.rs +++ b/crates/apub/src/protocol/activities/deletion/delete.rs @@ -48,7 +48,7 @@ impl InCommunity for Delete { let community_id = match DeletableObjects::read_from_db(self.object.id(), context).await? { DeletableObjects::Community(c) => c.id, DeletableObjects::Comment(c) => { - let post = Post::read(context.conn().await?, c.post_id).await?; + let post = Post::read(context.pool(), c.post_id).await?; post.community_id } DeletableObjects::Post(p) => p.community_id, @@ -56,7 +56,7 @@ impl InCommunity for Delete { return Err(anyhow!("Private message is not part of community").into()) } }; - let community = Community::read(context.conn().await?, community_id).await?; + let community = Community::read(context.pool(), community_id).await?; if let Some(audience) = &self.audience { verify_community_matches(audience, community.actor_id.clone())?; } diff --git a/crates/apub/src/protocol/collections/group_followers.rs b/crates/apub/src/protocol/collections/group_followers.rs index f0f69ad11..c7df8df2b 100644 --- a/crates/apub/src/protocol/collections/group_followers.rs +++ b/crates/apub/src/protocol/collections/group_followers.rs @@ -22,7 +22,7 @@ impl GroupFollowers { ) -> Result { let community_id = community.id; let community_followers = - CommunityFollowerView::for_community(context.conn().await?, community_id).await?; + CommunityFollowerView::for_community(context.pool(), community_id).await?; Ok(GroupFollowers { id: generate_followers_url(&community.actor_id)?.into(), diff --git a/crates/apub/src/protocol/objects/mod.rs b/crates/apub/src/protocol/objects/mod.rs index b525b6638..f35140a9b 100644 --- a/crates/apub/src/protocol/objects/mod.rs +++ b/crates/apub/src/protocol/objects/mod.rs @@ -2,7 +2,7 @@ use lemmy_db_schema::{ impls::actor_language::UNDETERMINED_ID, newtypes::LanguageId, source::language::Language, - utils::GetConn, + utils::DbPool, }; use lemmy_utils::error::LemmyError; use serde::{Deserialize, Serialize}; @@ -33,9 +33,9 @@ pub(crate) struct LanguageTag { impl LanguageTag { pub(crate) async fn new_single( lang: LanguageId, - mut conn: impl GetConn, + pool: &DbPool, ) -> Result, LemmyError> { - let lang = Language::read_from_id(conn, lang).await?; + let lang = Language::read_from_id(pool, lang).await?; // undetermined if lang.id == UNDETERMINED_ID { @@ -50,12 +50,12 @@ impl LanguageTag { pub(crate) async fn new_multiple( lang_ids: Vec, - mut conn: impl GetConn, + pool: &DbPool, ) -> Result, LemmyError> { let mut langs = Vec::::new(); for l in lang_ids { - langs.push(Language::read_from_id(conn, l).await?); + langs.push(Language::read_from_id(pool, l).await?); } let langs = langs @@ -70,23 +70,23 @@ impl LanguageTag { pub(crate) async fn to_language_id_single( lang: Option, - mut conn: impl GetConn, + pool: &DbPool, ) -> Result, LemmyError> { let identifier = lang.map(|l| l.identifier); - let language = Language::read_id_from_code(conn, identifier.as_deref()).await?; + let language = Language::read_id_from_code(pool, identifier.as_deref()).await?; Ok(language) } pub(crate) async fn to_language_id_multiple( langs: Vec, - mut conn: impl GetConn, + pool: &DbPool, ) -> Result, LemmyError> { let mut language_ids = Vec::new(); for l in langs { let id = l.identifier; - language_ids.push(Language::read_id_from_code(conn, Some(&id)).await?); + language_ids.push(Language::read_id_from_code(pool, Some(&id)).await?); } Ok(language_ids.into_iter().flatten().collect()) diff --git a/crates/apub/src/protocol/objects/note.rs b/crates/apub/src/protocol/objects/note.rs index 1526cf699..de90636e6 100644 --- a/crates/apub/src/protocol/objects/note.rs +++ b/crates/apub/src/protocol/objects/note.rs @@ -64,7 +64,7 @@ impl Note { PostOrComment::Post(p) => Ok((p.clone(), None)), PostOrComment::Comment(c) => { let post_id = c.post_id; - let post = Post::read(context.conn().await?, post_id).await?; + let post = Post::read(context.pool(), post_id).await?; Ok((post.into(), Some(c.clone()))) } } @@ -75,7 +75,7 @@ impl Note { impl InCommunity for Note { async fn community(&self, context: &Data) -> Result { let (post, _) = self.get_parents(context).await?; - let community = Community::read(context.conn().await?, post.community_id).await?; + let community = Community::read(context.pool(), post.community_id).await?; if let Some(audience) = &self.audience { verify_community_matches(audience, community.actor_id.clone())?; } diff --git a/crates/db_schema/src/aggregates/comment_aggregates.rs b/crates/db_schema/src/aggregates/comment_aggregates.rs index 83ea658e7..5a5550a2e 100644 --- a/crates/db_schema/src/aggregates/comment_aggregates.rs +++ b/crates/db_schema/src/aggregates/comment_aggregates.rs @@ -2,23 +2,23 @@ use crate::{ aggregates::structs::CommentAggregates, newtypes::CommentId, schema::comment_aggregates, - utils::{functions::hot_rank, GetConn}, + utils::{functions::hot_rank, get_conn, DbPool}, }; use diesel::{result::Error, ExpressionMethods, QueryDsl}; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::RunQueryDsl; impl CommentAggregates { - pub async fn read(mut conn: impl GetConn, comment_id: CommentId) -> Result { + pub async fn read(pool: &DbPool, comment_id: CommentId) -> Result { + let conn = &mut get_conn(pool).await?; comment_aggregates::table .filter(comment_aggregates::comment_id.eq(comment_id)) .first::(conn) .await } - pub async fn update_hot_rank( - mut conn: impl GetConn, - comment_id: CommentId, - ) -> Result { + pub async fn update_hot_rank(pool: &DbPool, comment_id: CommentId) -> Result { + let conn = &mut get_conn(pool).await?; + diesel::update(comment_aggregates::table) .filter(comment_aggregates::comment_id.eq(comment_id)) .set(comment_aggregates::hot_rank.eq(hot_rank( @@ -42,16 +42,16 @@ mod tests { post::{Post, PostInsertForm}, }, traits::{Crud, Likeable}, - utils::build_db_conn_for_tests, + utils::build_db_pool_for_tests, }; use serial_test::serial; #[tokio::test] #[serial] async fn test_crud() { - let mut conn = build_db_conn_for_tests().await; + let pool = &build_db_pool_for_tests().await; - let inserted_instance = Instance::read_or_create(conn, "my_domain.tld".to_string()) + let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()) .await .unwrap(); @@ -61,7 +61,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_person = Person::create(conn, &new_person).await.unwrap(); + let inserted_person = Person::create(pool, &new_person).await.unwrap(); let another_person = PersonInsertForm::builder() .name("jerry_comment_agg".into()) @@ -69,7 +69,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let another_inserted_person = Person::create(conn, &another_person).await.unwrap(); + let another_inserted_person = Person::create(pool, &another_person).await.unwrap(); let new_community = CommunityInsertForm::builder() .name("TIL_comment_agg".into()) @@ -78,7 +78,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_community = Community::create(conn, &new_community).await.unwrap(); + let inserted_community = Community::create(pool, &new_community).await.unwrap(); let new_post = PostInsertForm::builder() .name("A test post".into()) @@ -86,7 +86,7 @@ mod tests { .community_id(inserted_community.id) .build(); - let inserted_post = Post::create(conn, &new_post).await.unwrap(); + let inserted_post = Post::create(pool, &new_post).await.unwrap(); let comment_form = CommentInsertForm::builder() .content("A test comment".into()) @@ -94,9 +94,7 @@ mod tests { .post_id(inserted_post.id) .build(); - let inserted_comment = Comment::create(conn, &comment_form, None) - .await - .unwrap(); + let inserted_comment = Comment::create(pool, &comment_form, None).await.unwrap(); let child_comment_form = CommentInsertForm::builder() .content("A test comment".into()) @@ -104,13 +102,10 @@ mod tests { .post_id(inserted_post.id) .build(); - let _inserted_child_comment = Comment::create( - conn, - &child_comment_form, - Some(&inserted_comment.path), - ) - .await - .unwrap(); + let _inserted_child_comment = + Comment::create(pool, &child_comment_form, Some(&inserted_comment.path)) + .await + .unwrap(); let comment_like = CommentLikeForm { comment_id: inserted_comment.id, @@ -119,9 +114,9 @@ mod tests { score: 1, }; - CommentLike::like(conn, &comment_like).await.unwrap(); + CommentLike::like(pool, &comment_like).await.unwrap(); - let comment_aggs_before_delete = CommentAggregates::read(conn, inserted_comment.id) + let comment_aggs_before_delete = CommentAggregates::read(pool, inserted_comment.id) .await .unwrap(); @@ -137,11 +132,9 @@ mod tests { score: -1, }; - CommentLike::like(conn, &comment_dislike) - .await - .unwrap(); + CommentLike::like(pool, &comment_dislike).await.unwrap(); - let comment_aggs_after_dislike = CommentAggregates::read(conn, inserted_comment.id) + let comment_aggs_after_dislike = CommentAggregates::read(pool, inserted_comment.id) .await .unwrap(); @@ -150,10 +143,10 @@ mod tests { assert_eq!(1, comment_aggs_after_dislike.downvotes); // Remove the first comment like - CommentLike::remove(conn, inserted_person.id, inserted_comment.id) + CommentLike::remove(pool, inserted_person.id, inserted_comment.id) .await .unwrap(); - let after_like_remove = CommentAggregates::read(conn, inserted_comment.id) + let after_like_remove = CommentAggregates::read(pool, inserted_comment.id) .await .unwrap(); assert_eq!(-1, after_like_remove.score); @@ -161,29 +154,25 @@ mod tests { assert_eq!(1, after_like_remove.downvotes); // Remove the parent post - Post::delete(conn, inserted_post.id).await.unwrap(); + Post::delete(pool, inserted_post.id).await.unwrap(); // Should be none found, since the post was deleted - let after_delete = CommentAggregates::read(conn, inserted_comment.id).await; + let after_delete = CommentAggregates::read(pool, inserted_comment.id).await; assert!(after_delete.is_err()); // This should delete all the associated rows, and fire triggers - Person::delete(conn, another_inserted_person.id) - .await - .unwrap(); - let person_num_deleted = Person::delete(conn, inserted_person.id) + Person::delete(pool, another_inserted_person.id) .await .unwrap(); + let person_num_deleted = Person::delete(pool, inserted_person.id).await.unwrap(); assert_eq!(1, person_num_deleted); // Delete the community - let community_num_deleted = Community::delete(conn, inserted_community.id) + let community_num_deleted = Community::delete(pool, inserted_community.id) .await .unwrap(); assert_eq!(1, community_num_deleted); - Instance::delete(conn, inserted_instance.id) - .await - .unwrap(); + Instance::delete(pool, inserted_instance.id).await.unwrap(); } } diff --git a/crates/db_schema/src/aggregates/community_aggregates.rs b/crates/db_schema/src/aggregates/community_aggregates.rs index 16a48ba72..2c2eaa781 100644 --- a/crates/db_schema/src/aggregates/community_aggregates.rs +++ b/crates/db_schema/src/aggregates/community_aggregates.rs @@ -2,13 +2,14 @@ use crate::{ aggregates::structs::CommunityAggregates, newtypes::CommunityId, schema::community_aggregates, - utils::GetConn, + utils::{get_conn, DbPool}, }; use diesel::{result::Error, ExpressionMethods, QueryDsl}; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::RunQueryDsl; impl CommunityAggregates { - pub async fn read(mut conn: impl GetConn, community_id: CommunityId) -> Result { + pub async fn read(pool: &DbPool, community_id: CommunityId) -> Result { + let conn = &mut get_conn(pool).await?; community_aggregates::table .filter(community_aggregates::community_id.eq(community_id)) .first::(conn) @@ -28,16 +29,16 @@ mod tests { post::{Post, PostInsertForm}, }, traits::{Crud, Followable}, - utils::build_db_conn_for_tests, + utils::build_db_pool_for_tests, }; use serial_test::serial; #[tokio::test] #[serial] async fn test_crud() { - let mut conn = build_db_conn_for_tests().await; + let pool = &build_db_pool_for_tests().await; - let inserted_instance = Instance::read_or_create(conn, "my_domain.tld".to_string()) + let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()) .await .unwrap(); @@ -47,7 +48,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_person = Person::create(conn, &new_person).await.unwrap(); + let inserted_person = Person::create(pool, &new_person).await.unwrap(); let another_person = PersonInsertForm::builder() .name("jerry_community_agg".into()) @@ -55,7 +56,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let another_inserted_person = Person::create(conn, &another_person).await.unwrap(); + let another_inserted_person = Person::create(pool, &another_person).await.unwrap(); let new_community = CommunityInsertForm::builder() .name("TIL_community_agg".into()) @@ -64,7 +65,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_community = Community::create(conn, &new_community).await.unwrap(); + let inserted_community = Community::create(pool, &new_community).await.unwrap(); let another_community = CommunityInsertForm::builder() .name("TIL_community_agg_2".into()) @@ -73,9 +74,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let another_inserted_community = Community::create(conn, &another_community) - .await - .unwrap(); + let another_inserted_community = Community::create(pool, &another_community).await.unwrap(); let first_person_follow = CommunityFollowerForm { community_id: inserted_community.id, @@ -83,7 +82,7 @@ mod tests { pending: false, }; - CommunityFollower::follow(conn, &first_person_follow) + CommunityFollower::follow(pool, &first_person_follow) .await .unwrap(); @@ -93,7 +92,7 @@ mod tests { pending: false, }; - CommunityFollower::follow(conn, &second_person_follow) + CommunityFollower::follow(pool, &second_person_follow) .await .unwrap(); @@ -103,7 +102,7 @@ mod tests { pending: false, }; - CommunityFollower::follow(conn, &another_community_follow) + CommunityFollower::follow(pool, &another_community_follow) .await .unwrap(); @@ -113,7 +112,7 @@ mod tests { .community_id(inserted_community.id) .build(); - let inserted_post = Post::create(conn, &new_post).await.unwrap(); + let inserted_post = Post::create(pool, &new_post).await.unwrap(); let comment_form = CommentInsertForm::builder() .content("A test comment".into()) @@ -121,9 +120,7 @@ mod tests { .post_id(inserted_post.id) .build(); - let inserted_comment = Comment::create(conn, &comment_form, None) - .await - .unwrap(); + let inserted_comment = Comment::create(pool, &comment_form, None).await.unwrap(); let child_comment_form = CommentInsertForm::builder() .content("A test comment".into()) @@ -131,87 +128,79 @@ mod tests { .post_id(inserted_post.id) .build(); - let _inserted_child_comment = Comment::create( - conn, - &child_comment_form, - Some(&inserted_comment.path), - ) - .await - .unwrap(); - - let community_aggregates_before_delete = - CommunityAggregates::read(conn, inserted_community.id) + let _inserted_child_comment = + Comment::create(pool, &child_comment_form, Some(&inserted_comment.path)) .await .unwrap(); + let community_aggregates_before_delete = CommunityAggregates::read(pool, inserted_community.id) + .await + .unwrap(); + assert_eq!(2, community_aggregates_before_delete.subscribers); assert_eq!(1, community_aggregates_before_delete.posts); assert_eq!(2, community_aggregates_before_delete.comments); // Test the other community - let another_community_aggs = - CommunityAggregates::read(conn, another_inserted_community.id) - .await - .unwrap(); + let another_community_aggs = CommunityAggregates::read(pool, another_inserted_community.id) + .await + .unwrap(); assert_eq!(1, another_community_aggs.subscribers); assert_eq!(0, another_community_aggs.posts); assert_eq!(0, another_community_aggs.comments); // Unfollow test - CommunityFollower::unfollow(conn, &second_person_follow) + CommunityFollower::unfollow(pool, &second_person_follow) .await .unwrap(); - let after_unfollow = CommunityAggregates::read(conn, inserted_community.id) + let after_unfollow = CommunityAggregates::read(pool, inserted_community.id) .await .unwrap(); assert_eq!(1, after_unfollow.subscribers); // Follow again just for the later tests - CommunityFollower::follow(conn, &second_person_follow) + CommunityFollower::follow(pool, &second_person_follow) .await .unwrap(); - let after_follow_again = CommunityAggregates::read(conn, inserted_community.id) + let after_follow_again = CommunityAggregates::read(pool, inserted_community.id) .await .unwrap(); assert_eq!(2, after_follow_again.subscribers); // Remove a parent comment (the comment count should also be 0) - Post::delete(conn, inserted_post.id).await.unwrap(); - let after_parent_post_delete = CommunityAggregates::read(conn, inserted_community.id) + Post::delete(pool, inserted_post.id).await.unwrap(); + let after_parent_post_delete = CommunityAggregates::read(pool, inserted_community.id) .await .unwrap(); assert_eq!(0, after_parent_post_delete.comments); assert_eq!(0, after_parent_post_delete.posts); // Remove the 2nd person - Person::delete(conn, another_inserted_person.id) + Person::delete(pool, another_inserted_person.id) .await .unwrap(); - let after_person_delete = CommunityAggregates::read(conn, inserted_community.id) + let after_person_delete = CommunityAggregates::read(pool, inserted_community.id) .await .unwrap(); assert_eq!(1, after_person_delete.subscribers); // This should delete all the associated rows, and fire triggers - let person_num_deleted = Person::delete(conn, inserted_person.id) - .await - .unwrap(); + let person_num_deleted = Person::delete(pool, inserted_person.id).await.unwrap(); assert_eq!(1, person_num_deleted); // Delete the community - let community_num_deleted = Community::delete(conn, inserted_community.id) + let community_num_deleted = Community::delete(pool, inserted_community.id) .await .unwrap(); assert_eq!(1, community_num_deleted); - let another_community_num_deleted = - Community::delete(conn, another_inserted_community.id) - .await - .unwrap(); + let another_community_num_deleted = Community::delete(pool, another_inserted_community.id) + .await + .unwrap(); assert_eq!(1, another_community_num_deleted); // Should be none found, since the creator was deleted - let after_delete = CommunityAggregates::read(conn, inserted_community.id).await; + let after_delete = CommunityAggregates::read(pool, inserted_community.id).await; assert!(after_delete.is_err()); } } diff --git a/crates/db_schema/src/aggregates/person_aggregates.rs b/crates/db_schema/src/aggregates/person_aggregates.rs index ff8547338..295f1bfbb 100644 --- a/crates/db_schema/src/aggregates/person_aggregates.rs +++ b/crates/db_schema/src/aggregates/person_aggregates.rs @@ -2,13 +2,14 @@ use crate::{ aggregates::structs::PersonAggregates, newtypes::PersonId, schema::person_aggregates, - utils::GetConn, + utils::{get_conn, DbPool}, }; use diesel::{result::Error, ExpressionMethods, QueryDsl}; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::RunQueryDsl; impl PersonAggregates { - pub async fn read(mut conn: impl GetConn, person_id: PersonId) -> Result { + pub async fn read(pool: &DbPool, person_id: PersonId) -> Result { + let conn = &mut get_conn(pool).await?; person_aggregates::table .filter(person_aggregates::person_id.eq(person_id)) .first::(conn) @@ -28,16 +29,16 @@ mod tests { post::{Post, PostInsertForm, PostLike, PostLikeForm}, }, traits::{Crud, Likeable}, - utils::build_db_conn_for_tests, + utils::build_db_pool_for_tests, }; use serial_test::serial; #[tokio::test] #[serial] async fn test_crud() { - let mut conn = build_db_conn_for_tests().await; + let pool = &build_db_pool_for_tests().await; - let inserted_instance = Instance::read_or_create(conn, "my_domain.tld".to_string()) + let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()) .await .unwrap(); @@ -47,7 +48,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_person = Person::create(conn, &new_person).await.unwrap(); + let inserted_person = Person::create(pool, &new_person).await.unwrap(); let another_person = PersonInsertForm::builder() .name("jerry_user_agg".into()) @@ -55,7 +56,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let another_inserted_person = Person::create(conn, &another_person).await.unwrap(); + let another_inserted_person = Person::create(pool, &another_person).await.unwrap(); let new_community = CommunityInsertForm::builder() .name("TIL_site_agg".into()) @@ -64,7 +65,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_community = Community::create(conn, &new_community).await.unwrap(); + let inserted_community = Community::create(pool, &new_community).await.unwrap(); let new_post = PostInsertForm::builder() .name("A test post".into()) @@ -72,7 +73,7 @@ mod tests { .community_id(inserted_community.id) .build(); - let inserted_post = Post::create(conn, &new_post).await.unwrap(); + let inserted_post = Post::create(pool, &new_post).await.unwrap(); let post_like = PostLikeForm { post_id: inserted_post.id, @@ -80,7 +81,7 @@ mod tests { score: 1, }; - let _inserted_post_like = PostLike::like(conn, &post_like).await.unwrap(); + let _inserted_post_like = PostLike::like(pool, &post_like).await.unwrap(); let comment_form = CommentInsertForm::builder() .content("A test comment".into()) @@ -88,9 +89,7 @@ mod tests { .post_id(inserted_post.id) .build(); - let inserted_comment = Comment::create(conn, &comment_form, None) - .await - .unwrap(); + let inserted_comment = Comment::create(pool, &comment_form, None).await.unwrap(); let mut comment_like = CommentLikeForm { comment_id: inserted_comment.id, @@ -99,7 +98,7 @@ mod tests { score: 1, }; - let _inserted_comment_like = CommentLike::like(conn, &comment_like).await.unwrap(); + let _inserted_comment_like = CommentLike::like(pool, &comment_like).await.unwrap(); let child_comment_form = CommentInsertForm::builder() .content("A test comment".into()) @@ -107,13 +106,10 @@ mod tests { .post_id(inserted_post.id) .build(); - let inserted_child_comment = Comment::create( - conn, - &child_comment_form, - Some(&inserted_comment.path), - ) - .await - .unwrap(); + let inserted_child_comment = + Comment::create(pool, &child_comment_form, Some(&inserted_comment.path)) + .await + .unwrap(); let child_comment_like = CommentLikeForm { comment_id: inserted_child_comment.id, @@ -122,11 +118,9 @@ mod tests { score: 1, }; - let _inserted_child_comment_like = CommentLike::like(conn, &child_comment_like) - .await - .unwrap(); + let _inserted_child_comment_like = CommentLike::like(pool, &child_comment_like).await.unwrap(); - let person_aggregates_before_delete = PersonAggregates::read(conn, inserted_person.id) + let person_aggregates_before_delete = PersonAggregates::read(pool, inserted_person.id) .await .unwrap(); @@ -136,69 +130,62 @@ mod tests { assert_eq!(2, person_aggregates_before_delete.comment_score); // Remove a post like - PostLike::remove(conn, inserted_person.id, inserted_post.id) + PostLike::remove(pool, inserted_person.id, inserted_post.id) .await .unwrap(); - let after_post_like_remove = PersonAggregates::read(conn, inserted_person.id) + let after_post_like_remove = PersonAggregates::read(pool, inserted_person.id) .await .unwrap(); assert_eq!(0, after_post_like_remove.post_score); Comment::update( - conn, + pool, inserted_comment.id, &CommentUpdateForm::builder().removed(Some(true)).build(), ) .await .unwrap(); Comment::update( - conn, + pool, inserted_child_comment.id, &CommentUpdateForm::builder().removed(Some(true)).build(), ) .await .unwrap(); - let after_parent_comment_removed = PersonAggregates::read(conn, inserted_person.id) + let after_parent_comment_removed = PersonAggregates::read(pool, inserted_person.id) .await .unwrap(); assert_eq!(0, after_parent_comment_removed.comment_count); assert_eq!(0, after_parent_comment_removed.comment_score); // Remove a parent comment (the scores should also be removed) - Comment::delete(conn, inserted_comment.id) + Comment::delete(pool, inserted_comment.id).await.unwrap(); + Comment::delete(pool, inserted_child_comment.id) .await .unwrap(); - Comment::delete(conn, inserted_child_comment.id) - .await - .unwrap(); - let after_parent_comment_delete = PersonAggregates::read(conn, inserted_person.id) + let after_parent_comment_delete = PersonAggregates::read(pool, inserted_person.id) .await .unwrap(); assert_eq!(0, after_parent_comment_delete.comment_count); assert_eq!(0, after_parent_comment_delete.comment_score); // Add in the two comments again, then delete the post. - let new_parent_comment = Comment::create(conn, &comment_form, None) - .await - .unwrap(); - let _new_child_comment = Comment::create( - conn, - &child_comment_form, - Some(&new_parent_comment.path), - ) - .await - .unwrap(); + let new_parent_comment = Comment::create(pool, &comment_form, None).await.unwrap(); + let _new_child_comment = + Comment::create(pool, &child_comment_form, Some(&new_parent_comment.path)) + .await + .unwrap(); comment_like.comment_id = new_parent_comment.id; - CommentLike::like(conn, &comment_like).await.unwrap(); - let after_comment_add = PersonAggregates::read(conn, inserted_person.id) + CommentLike::like(pool, &comment_like).await.unwrap(); + let after_comment_add = PersonAggregates::read(pool, inserted_person.id) .await .unwrap(); assert_eq!(2, after_comment_add.comment_count); assert_eq!(1, after_comment_add.comment_score); - Post::delete(conn, inserted_post.id).await.unwrap(); - let after_post_delete = PersonAggregates::read(conn, inserted_person.id) + Post::delete(pool, inserted_post.id).await.unwrap(); + let after_post_delete = PersonAggregates::read(pool, inserted_person.id) .await .unwrap(); assert_eq!(0, after_post_delete.comment_score); @@ -207,26 +194,22 @@ mod tests { assert_eq!(0, after_post_delete.post_count); // This should delete all the associated rows, and fire triggers - let person_num_deleted = Person::delete(conn, inserted_person.id) - .await - .unwrap(); + let person_num_deleted = Person::delete(pool, inserted_person.id).await.unwrap(); assert_eq!(1, person_num_deleted); - Person::delete(conn, another_inserted_person.id) + Person::delete(pool, another_inserted_person.id) .await .unwrap(); // Delete the community - let community_num_deleted = Community::delete(conn, inserted_community.id) + let community_num_deleted = Community::delete(pool, inserted_community.id) .await .unwrap(); assert_eq!(1, community_num_deleted); // Should be none found - let after_delete = PersonAggregates::read(conn, inserted_person.id).await; + let after_delete = PersonAggregates::read(pool, inserted_person.id).await; assert!(after_delete.is_err()); - Instance::delete(conn, inserted_instance.id) - .await - .unwrap(); + Instance::delete(pool, inserted_instance.id).await.unwrap(); } } diff --git a/crates/db_schema/src/aggregates/person_post_aggregates.rs b/crates/db_schema/src/aggregates/person_post_aggregates.rs index 282ce79cb..5fe1aacff 100644 --- a/crates/db_schema/src/aggregates/person_post_aggregates.rs +++ b/crates/db_schema/src/aggregates/person_post_aggregates.rs @@ -3,16 +3,14 @@ use crate::{ diesel::BoolExpressionMethods, newtypes::{PersonId, PostId}, schema::person_post_aggregates::dsl::{person_id, person_post_aggregates, post_id}, - utils::GetConn, + utils::{get_conn, DbPool}, }; use diesel::{insert_into, result::Error, ExpressionMethods, QueryDsl}; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::RunQueryDsl; impl PersonPostAggregates { - pub async fn upsert( - mut conn: impl GetConn, - form: &PersonPostAggregatesForm, - ) -> Result { + pub async fn upsert(pool: &DbPool, form: &PersonPostAggregatesForm) -> Result { + let conn = &mut get_conn(pool).await?; insert_into(person_post_aggregates) .values(form) .on_conflict((person_id, post_id)) @@ -21,11 +19,8 @@ impl PersonPostAggregates { .get_result::(conn) .await } - pub async fn read( - mut conn: impl GetConn, - person_id_: PersonId, - post_id_: PostId, - ) -> Result { + pub async fn read(pool: &DbPool, person_id_: PersonId, post_id_: PostId) -> Result { + let conn = &mut get_conn(pool).await?; person_post_aggregates .filter(post_id.eq(post_id_).and(person_id.eq(person_id_))) .first::(conn) diff --git a/crates/db_schema/src/aggregates/post_aggregates.rs b/crates/db_schema/src/aggregates/post_aggregates.rs index ad39bcce1..176f694a7 100644 --- a/crates/db_schema/src/aggregates/post_aggregates.rs +++ b/crates/db_schema/src/aggregates/post_aggregates.rs @@ -2,20 +2,23 @@ use crate::{ aggregates::structs::PostAggregates, newtypes::PostId, schema::post_aggregates, - utils::{functions::hot_rank, GetConn}, + utils::{functions::hot_rank, get_conn, DbPool}, }; use diesel::{result::Error, ExpressionMethods, QueryDsl}; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::RunQueryDsl; impl PostAggregates { - pub async fn read(mut conn: impl GetConn, post_id: PostId) -> Result { + pub async fn read(pool: &DbPool, post_id: PostId) -> Result { + let conn = &mut get_conn(pool).await?; post_aggregates::table .filter(post_aggregates::post_id.eq(post_id)) .first::(conn) .await } - pub async fn update_hot_rank(mut conn: impl GetConn, post_id: PostId) -> Result { + pub async fn update_hot_rank(pool: &DbPool, post_id: PostId) -> Result { + let conn = &mut get_conn(pool).await?; + diesel::update(post_aggregates::table) .filter(post_aggregates::post_id.eq(post_id)) .set(( @@ -42,16 +45,16 @@ mod tests { post::{Post, PostInsertForm, PostLike, PostLikeForm}, }, traits::{Crud, Likeable}, - utils::build_db_conn_for_tests, + utils::build_db_pool_for_tests, }; use serial_test::serial; #[tokio::test] #[serial] async fn test_crud() { - let mut conn = build_db_conn_for_tests().await; + let pool = &build_db_pool_for_tests().await; - let inserted_instance = Instance::read_or_create(conn, "my_domain.tld".to_string()) + let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()) .await .unwrap(); @@ -61,7 +64,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_person = Person::create(conn, &new_person).await.unwrap(); + let inserted_person = Person::create(pool, &new_person).await.unwrap(); let another_person = PersonInsertForm::builder() .name("jerry_community_agg".into()) @@ -69,7 +72,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let another_inserted_person = Person::create(conn, &another_person).await.unwrap(); + let another_inserted_person = Person::create(pool, &another_person).await.unwrap(); let new_community = CommunityInsertForm::builder() .name("TIL_community_agg".into()) @@ -78,7 +81,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_community = Community::create(conn, &new_community).await.unwrap(); + let inserted_community = Community::create(pool, &new_community).await.unwrap(); let new_post = PostInsertForm::builder() .name("A test post".into()) @@ -86,7 +89,7 @@ mod tests { .community_id(inserted_community.id) .build(); - let inserted_post = Post::create(conn, &new_post).await.unwrap(); + let inserted_post = Post::create(pool, &new_post).await.unwrap(); let comment_form = CommentInsertForm::builder() .content("A test comment".into()) @@ -94,9 +97,7 @@ mod tests { .post_id(inserted_post.id) .build(); - let inserted_comment = Comment::create(conn, &comment_form, None) - .await - .unwrap(); + let inserted_comment = Comment::create(pool, &comment_form, None).await.unwrap(); let child_comment_form = CommentInsertForm::builder() .content("A test comment".into()) @@ -104,13 +105,10 @@ mod tests { .post_id(inserted_post.id) .build(); - let inserted_child_comment = Comment::create( - conn, - &child_comment_form, - Some(&inserted_comment.path), - ) - .await - .unwrap(); + let inserted_child_comment = + Comment::create(pool, &child_comment_form, Some(&inserted_comment.path)) + .await + .unwrap(); let post_like = PostLikeForm { post_id: inserted_post.id, @@ -118,11 +116,9 @@ mod tests { score: 1, }; - PostLike::like(conn, &post_like).await.unwrap(); + PostLike::like(pool, &post_like).await.unwrap(); - let post_aggs_before_delete = PostAggregates::read(conn, inserted_post.id) - .await - .unwrap(); + let post_aggs_before_delete = PostAggregates::read(pool, inserted_post.id).await.unwrap(); assert_eq!(2, post_aggs_before_delete.comments); assert_eq!(1, post_aggs_before_delete.score); @@ -136,11 +132,9 @@ mod tests { score: -1, }; - PostLike::like(conn, &post_dislike).await.unwrap(); + PostLike::like(pool, &post_dislike).await.unwrap(); - let post_aggs_after_dislike = PostAggregates::read(conn, inserted_post.id) - .await - .unwrap(); + let post_aggs_after_dislike = PostAggregates::read(pool, inserted_post.id).await.unwrap(); assert_eq!(2, post_aggs_after_dislike.comments); assert_eq!(0, post_aggs_after_dislike.score); @@ -148,53 +142,43 @@ mod tests { assert_eq!(1, post_aggs_after_dislike.downvotes); // Remove the comments - Comment::delete(conn, inserted_comment.id) - .await - .unwrap(); - Comment::delete(conn, inserted_child_comment.id) - .await - .unwrap(); - let after_comment_delete = PostAggregates::read(conn, inserted_post.id) + Comment::delete(pool, inserted_comment.id).await.unwrap(); + Comment::delete(pool, inserted_child_comment.id) .await .unwrap(); + let after_comment_delete = PostAggregates::read(pool, inserted_post.id).await.unwrap(); assert_eq!(0, after_comment_delete.comments); assert_eq!(0, after_comment_delete.score); assert_eq!(1, after_comment_delete.upvotes); assert_eq!(1, after_comment_delete.downvotes); // Remove the first post like - PostLike::remove(conn, inserted_person.id, inserted_post.id) - .await - .unwrap(); - let after_like_remove = PostAggregates::read(conn, inserted_post.id) + PostLike::remove(pool, inserted_person.id, inserted_post.id) .await .unwrap(); + let after_like_remove = PostAggregates::read(pool, inserted_post.id).await.unwrap(); assert_eq!(0, after_like_remove.comments); assert_eq!(-1, after_like_remove.score); assert_eq!(0, after_like_remove.upvotes); assert_eq!(1, after_like_remove.downvotes); // This should delete all the associated rows, and fire triggers - Person::delete(conn, another_inserted_person.id) - .await - .unwrap(); - let person_num_deleted = Person::delete(conn, inserted_person.id) + Person::delete(pool, another_inserted_person.id) .await .unwrap(); + let person_num_deleted = Person::delete(pool, inserted_person.id).await.unwrap(); assert_eq!(1, person_num_deleted); // Delete the community - let community_num_deleted = Community::delete(conn, inserted_community.id) + let community_num_deleted = Community::delete(pool, inserted_community.id) .await .unwrap(); assert_eq!(1, community_num_deleted); // Should be none found, since the creator was deleted - let after_delete = PostAggregates::read(conn, inserted_post.id).await; + let after_delete = PostAggregates::read(pool, inserted_post.id).await; assert!(after_delete.is_err()); - Instance::delete(conn, inserted_instance.id) - .await - .unwrap(); + Instance::delete(pool, inserted_instance.id).await.unwrap(); } } diff --git a/crates/db_schema/src/aggregates/site_aggregates.rs b/crates/db_schema/src/aggregates/site_aggregates.rs index 12db9d703..719beb8f7 100644 --- a/crates/db_schema/src/aggregates/site_aggregates.rs +++ b/crates/db_schema/src/aggregates/site_aggregates.rs @@ -1,9 +1,14 @@ -use crate::{aggregates::structs::SiteAggregates, schema::site_aggregates, utils::GetConn}; +use crate::{ + aggregates::structs::SiteAggregates, + schema::site_aggregates, + utils::{get_conn, DbPool}, +}; use diesel::result::Error; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::RunQueryDsl; impl SiteAggregates { - pub async fn read(mut conn: impl GetConn) -> Result { + pub async fn read(pool: &DbPool) -> Result { + let conn = &mut get_conn(pool).await?; site_aggregates::table.first::(conn).await } } @@ -21,16 +26,16 @@ mod tests { site::{Site, SiteInsertForm}, }, traits::Crud, - utils::build_db_conn_for_tests, + utils::build_db_pool_for_tests, }; use serial_test::serial; #[tokio::test] #[serial] async fn test_crud() { - let mut conn = build_db_conn_for_tests().await; + let pool = &build_db_pool_for_tests().await; - let inserted_instance = Instance::read_or_create(conn, "my_domain.tld".to_string()) + let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()) .await .unwrap(); @@ -40,14 +45,14 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_person = Person::create(conn, &new_person).await.unwrap(); + let inserted_person = Person::create(pool, &new_person).await.unwrap(); let site_form = SiteInsertForm::builder() .name("test_site".into()) .instance_id(inserted_instance.id) .build(); - let inserted_site = Site::create(conn, &site_form).await.unwrap(); + let inserted_site = Site::create(pool, &site_form).await.unwrap(); let new_community = CommunityInsertForm::builder() .name("TIL_site_agg".into()) @@ -56,7 +61,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_community = Community::create(conn, &new_community).await.unwrap(); + let inserted_community = Community::create(pool, &new_community).await.unwrap(); let new_post = PostInsertForm::builder() .name("A test post".into()) @@ -65,8 +70,8 @@ mod tests { .build(); // Insert two of those posts - let inserted_post = Post::create(conn, &new_post).await.unwrap(); - let _inserted_post_again = Post::create(conn, &new_post).await.unwrap(); + let inserted_post = Post::create(pool, &new_post).await.unwrap(); + let _inserted_post_again = Post::create(pool, &new_post).await.unwrap(); let comment_form = CommentInsertForm::builder() .content("A test comment".into()) @@ -75,9 +80,7 @@ mod tests { .build(); // Insert two of those comments - let inserted_comment = Comment::create(conn, &comment_form, None) - .await - .unwrap(); + let inserted_comment = Comment::create(pool, &comment_form, None).await.unwrap(); let child_comment_form = CommentInsertForm::builder() .content("A test comment".into()) @@ -85,15 +88,12 @@ mod tests { .post_id(inserted_post.id) .build(); - let _inserted_child_comment = Comment::create( - conn, - &child_comment_form, - Some(&inserted_comment.path), - ) - .await - .unwrap(); + let _inserted_child_comment = + Comment::create(pool, &child_comment_form, Some(&inserted_comment.path)) + .await + .unwrap(); - let site_aggregates_before_delete = SiteAggregates::read(conn).await.unwrap(); + let site_aggregates_before_delete = SiteAggregates::read(pool).await.unwrap(); // TODO: this is unstable, sometimes it returns 0 users, sometimes 1 //assert_eq!(0, site_aggregates_before_delete.users); @@ -102,33 +102,29 @@ mod tests { assert_eq!(2, site_aggregates_before_delete.comments); // Try a post delete - Post::delete(conn, inserted_post.id).await.unwrap(); - let site_aggregates_after_post_delete = SiteAggregates::read(conn).await.unwrap(); + Post::delete(pool, inserted_post.id).await.unwrap(); + let site_aggregates_after_post_delete = SiteAggregates::read(pool).await.unwrap(); assert_eq!(1, site_aggregates_after_post_delete.posts); assert_eq!(0, site_aggregates_after_post_delete.comments); // This shouuld delete all the associated rows, and fire triggers - let person_num_deleted = Person::delete(conn, inserted_person.id) - .await - .unwrap(); + let person_num_deleted = Person::delete(pool, inserted_person.id).await.unwrap(); assert_eq!(1, person_num_deleted); // Delete the community - let community_num_deleted = Community::delete(conn, inserted_community.id) + let community_num_deleted = Community::delete(pool, inserted_community.id) .await .unwrap(); assert_eq!(1, community_num_deleted); // Site should still exist, it can without a site creator. - let after_delete_creator = SiteAggregates::read(conn).await; + let after_delete_creator = SiteAggregates::read(pool).await; assert!(after_delete_creator.is_ok()); - Site::delete(conn, inserted_site.id).await.unwrap(); - let after_delete_site = SiteAggregates::read(conn).await; + Site::delete(pool, inserted_site.id).await.unwrap(); + let after_delete_site = SiteAggregates::read(pool).await; assert!(after_delete_site.is_err()); - Instance::delete(conn, inserted_instance.id) - .await - .unwrap(); + Instance::delete(pool, inserted_instance.id).await.unwrap(); } } diff --git a/crates/db_schema/src/impls/activity.rs b/crates/db_schema/src/impls/activity.rs index 1aaeaf7fc..9187e736c 100644 --- a/crates/db_schema/src/impls/activity.rs +++ b/crates/db_schema/src/impls/activity.rs @@ -3,21 +3,23 @@ use crate::{ schema::activity::dsl::{activity, ap_id}, source::activity::{Activity, ActivityInsertForm, ActivityUpdateForm}, traits::Crud, - utils::GetConn, + utils::{get_conn, DbPool}, }; use diesel::{dsl::insert_into, result::Error, ExpressionMethods, QueryDsl}; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::RunQueryDsl; #[async_trait] impl Crud for Activity { type InsertForm = ActivityInsertForm; type UpdateForm = ActivityUpdateForm; type IdType = i32; - async fn read(mut conn: impl GetConn, activity_id: i32) -> Result { + async fn read(pool: &DbPool, activity_id: i32) -> Result { + let conn = &mut get_conn(pool).await?; activity.find(activity_id).first::(conn).await } - async fn create(mut conn: impl GetConn, new_activity: &Self::InsertForm) -> Result { + async fn create(pool: &DbPool, new_activity: &Self::InsertForm) -> Result { + let conn = &mut get_conn(pool).await?; insert_into(activity) .values(new_activity) .get_result::(conn) @@ -25,16 +27,18 @@ impl Crud for Activity { } async fn update( - mut conn: impl GetConn, + pool: &DbPool, activity_id: i32, new_activity: &Self::UpdateForm, ) -> Result { + let conn = &mut get_conn(pool).await?; diesel::update(activity.find(activity_id)) .set(new_activity) .get_result::(conn) .await } - async fn delete(mut conn: impl GetConn, activity_id: i32) -> Result { + async fn delete(pool: &DbPool, activity_id: i32) -> Result { + let conn = &mut get_conn(pool).await?; diesel::delete(activity.find(activity_id)) .execute(conn) .await @@ -42,10 +46,8 @@ impl Crud for Activity { } impl Activity { - pub async fn read_from_apub_id( - mut conn: impl GetConn, - object_id: &DbUrl, - ) -> Result { + pub async fn read_from_apub_id(pool: &DbPool, object_id: &DbUrl) -> Result { + let conn = &mut get_conn(pool).await?; activity .filter(ap_id.eq(object_id)) .first::(conn) @@ -63,7 +65,7 @@ mod tests { instance::Instance, person::{Person, PersonInsertForm}, }, - utils::build_db_conn_for_tests, + utils::build_db_pool_for_tests, }; use serde_json::Value; use serial_test::serial; @@ -72,9 +74,9 @@ mod tests { #[tokio::test] #[serial] async fn test_crud() { - let mut conn = build_db_conn_for_tests().await; + let pool = &build_db_pool_for_tests().await; - let inserted_instance = Instance::read_or_create(conn, "my_domain.tld".to_string()) + let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()) .await .unwrap(); @@ -84,7 +86,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_creator = Person::create(conn, &creator_form).await.unwrap(); + let inserted_creator = Person::create(pool, &creator_form).await.unwrap(); let ap_id_: DbUrl = Url::parse( "https://enterprise.lemmy.ml/activities/delete/f1b5d57c-80f8-4e03-a615-688d552e946c", @@ -113,7 +115,7 @@ mod tests { updated: None, }; - let inserted_activity = Activity::create(conn, &activity_form).await.unwrap(); + let inserted_activity = Activity::create(pool, &activity_form).await.unwrap(); let expected_activity = Activity { ap_id: ap_id_.clone(), @@ -125,18 +127,10 @@ mod tests { updated: None, }; - let read_activity = Activity::read(conn, inserted_activity.id) - .await - .unwrap(); - let read_activity_by_apub_id = Activity::read_from_apub_id(conn, &ap_id_) - .await - .unwrap(); - Person::delete(conn, inserted_creator.id) - .await - .unwrap(); - Activity::delete(conn, inserted_activity.id) - .await - .unwrap(); + let read_activity = Activity::read(pool, inserted_activity.id).await.unwrap(); + let read_activity_by_apub_id = Activity::read_from_apub_id(pool, &ap_id_).await.unwrap(); + Person::delete(pool, inserted_creator.id).await.unwrap(); + Activity::delete(pool, inserted_activity.id).await.unwrap(); assert_eq!(expected_activity, read_activity); assert_eq!(expected_activity, read_activity_by_apub_id); diff --git a/crates/db_schema/src/impls/actor_language.rs b/crates/db_schema/src/impls/actor_language.rs index 6d819744a..dbb9c70fe 100644 --- a/crates/db_schema/src/impls/actor_language.rs +++ b/crates/db_schema/src/impls/actor_language.rs @@ -14,7 +14,7 @@ use crate::{ language::Language, site::Site, }, - utils::GetConn, + utils::{get_conn, DbPool}, }; use diesel::{ delete, @@ -25,7 +25,11 @@ use diesel::{ ExpressionMethods, QueryDsl, }; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::{ + pooled_connection::deadpool::Object as PooledConnection, + AsyncPgConnection, + RunQueryDsl, +}; use lemmy_utils::error::LemmyError; use tokio::sync::OnceCell; @@ -33,7 +37,7 @@ pub const UNDETERMINED_ID: LanguageId = LanguageId(0); impl LocalUserLanguage { pub async fn read( - mut conn: impl GetConn, + pool: &DbPool, for_local_user_id: LocalUserId, ) -> Result, Error> { use crate::schema::local_user_language::dsl::{ @@ -41,6 +45,7 @@ impl LocalUserLanguage { local_user_id, local_user_language, }; + let conn = &mut get_conn(pool).await?; conn .build_transaction() @@ -62,14 +67,15 @@ impl LocalUserLanguage { /// /// If no language_id vector is given, it will show all languages pub async fn update( - mut conn: impl GetConn, + pool: &DbPool, language_ids: Vec, for_local_user_id: LocalUserId, ) -> Result<(), Error> { + let conn = &mut get_conn(pool).await?; let mut lang_ids = convert_update_languages(conn, language_ids).await?; // No need to update if languages are unchanged - let current = LocalUserLanguage::read(conn, for_local_user_id).await?; + let current = LocalUserLanguage::read(pool, for_local_user_id).await?; if current == lang_ids { return Ok(()); } @@ -112,7 +118,8 @@ impl LocalUserLanguage { } impl SiteLanguage { - pub async fn read_local_raw(mut conn: impl GetConn) -> Result, Error> { + pub async fn read_local_raw(pool: &DbPool) -> Result, Error> { + let conn = &mut get_conn(pool).await?; site::table .inner_join(local_site::table) .inner_join(site_language::table) @@ -122,7 +129,10 @@ impl SiteLanguage { .await } - async fn read_raw(mut conn: impl GetConn, for_site_id: SiteId) -> Result, Error> { + async fn read_raw( + conn: &mut PooledConnection, + for_site_id: SiteId, + ) -> Result, Error> { site_language::table .filter(site_language::site_id.eq(for_site_id)) .order(site_language::language_id) @@ -131,23 +141,25 @@ impl SiteLanguage { .await } - pub async fn read(mut conn: impl GetConn, for_site_id: SiteId) -> Result, Error> { + pub async fn read(pool: &DbPool, for_site_id: SiteId) -> Result, Error> { + let conn = &mut get_conn(pool).await?; let langs = Self::read_raw(conn, for_site_id).await?; convert_read_languages(conn, langs).await } pub async fn update( - mut conn: impl GetConn, + pool: &DbPool, language_ids: Vec, site: &Site, ) -> Result<(), Error> { + let conn = &mut get_conn(pool).await?; let for_site_id = site.id; let instance_id = site.instance_id; let lang_ids = convert_update_languages(conn, language_ids).await?; // No need to update if languages are unchanged - let current = SiteLanguage::read(conn, site.id).await?; + let current = SiteLanguage::read(pool, site.id).await?; if current == lang_ids { return Ok(()); } @@ -186,11 +198,12 @@ impl SiteLanguage { impl CommunityLanguage { /// Returns true if the given language is one of configured languages for given community pub async fn is_allowed_community_language( - mut conn: impl GetConn, + pool: &DbPool, for_language_id: Option, for_community_id: CommunityId, ) -> Result<(), LemmyError> { use crate::schema::community_language::dsl::{community_id, community_language, language_id}; + let conn = &mut get_conn(pool).await?; if let Some(for_language_id) = for_language_id { let is_allowed = select(exists( @@ -216,7 +229,7 @@ impl CommunityLanguage { /// community language, and it shouldnt be possible to post content in languages which are not /// allowed by local site. async fn limit_languages( - mut conn: impl GetConn, + conn: &mut AsyncPgConnection, for_instance_id: InstanceId, ) -> Result<(), Error> { use crate::schema::{ @@ -242,7 +255,7 @@ impl CommunityLanguage { } async fn read_raw( - mut conn: impl GetConn, + conn: &mut PooledConnection, for_community_id: CommunityId, ) -> Result, Error> { use crate::schema::community_language::dsl::{community_id, community_language, language_id}; @@ -255,20 +268,22 @@ impl CommunityLanguage { } pub async fn read( - mut conn: impl GetConn, + pool: &DbPool, for_community_id: CommunityId, ) -> Result, Error> { + let conn = &mut get_conn(pool).await?; let langs = Self::read_raw(conn, for_community_id).await?; convert_read_languages(conn, langs).await } pub async fn update( - mut conn: impl GetConn, + pool: &DbPool, mut language_ids: Vec, for_community_id: CommunityId, ) -> Result<(), Error> { + let conn = &mut get_conn(pool).await?; if language_ids.is_empty() { - language_ids = SiteLanguage::read_local_raw(conn).await?; + language_ids = SiteLanguage::read_local_raw(pool).await?; } let lang_ids = convert_update_languages(conn, language_ids).await?; @@ -306,11 +321,12 @@ impl CommunityLanguage { } pub async fn default_post_language( - mut conn: impl GetConn, + pool: &DbPool, community_id: CommunityId, local_user_id: LocalUserId, ) -> Result, Error> { use crate::schema::{community_language::dsl as cl, local_user_language::dsl as ul}; + let conn = &mut get_conn(pool).await?; let mut intersection = ul::local_user_language .inner_join(cl::community_language.on(ul::language_id.eq(cl::language_id))) .filter(ul::local_user_id.eq(local_user_id)) @@ -331,7 +347,7 @@ pub async fn default_post_language( /// If no language is given, set all languages async fn convert_update_languages( - mut conn: impl GetConn, + conn: &mut AsyncPgConnection, language_ids: Vec, ) -> Result, Error> { if language_ids.is_empty() { @@ -349,7 +365,7 @@ async fn convert_update_languages( /// If all languages are returned, return empty vec instead async fn convert_read_languages( - mut conn: impl GetConn, + conn: &mut AsyncPgConnection, language_ids: Vec, ) -> Result, Error> { static ALL_LANGUAGES_COUNT: OnceCell = OnceCell::const_new(); @@ -380,8 +396,9 @@ mod tests { convert_read_languages, convert_update_languages, default_post_language, + get_conn, CommunityLanguage, - GetConn, + DbPool, Language, LanguageId, LocalUserLanguage, @@ -398,41 +415,41 @@ mod tests { site::{Site, SiteInsertForm}, }, traits::Crud, - utils::build_db_conn_for_tests, + utils::build_db_pool_for_tests, }; use serial_test::serial; - async fn test_langs1(mut conn: impl GetConn) -> Vec { + async fn test_langs1(pool: &DbPool) -> Vec { vec![ - Language::read_id_from_code(conn, Some("en")) + Language::read_id_from_code(pool, Some("en")) .await .unwrap() .unwrap(), - Language::read_id_from_code(conn, Some("fr")) + Language::read_id_from_code(pool, Some("fr")) .await .unwrap() .unwrap(), - Language::read_id_from_code(conn, Some("ru")) + Language::read_id_from_code(pool, Some("ru")) .await .unwrap() .unwrap(), ] } - async fn test_langs2(mut conn: impl GetConn) -> Vec { + async fn test_langs2(pool: &DbPool) -> Vec { vec![ - Language::read_id_from_code(conn, Some("fi")) + Language::read_id_from_code(pool, Some("fi")) .await .unwrap() .unwrap(), - Language::read_id_from_code(conn, Some("se")) + Language::read_id_from_code(pool, Some("se")) .await .unwrap() .unwrap(), ] } - async fn create_test_site(mut conn: impl GetConn) -> (Site, Instance) { - let inserted_instance = Instance::read_or_create(conn, "my_domain.tld".to_string()) + async fn create_test_site(pool: &DbPool) -> (Site, Instance) { + let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()) .await .unwrap(); @@ -440,13 +457,11 @@ mod tests { .name("test site".to_string()) .instance_id(inserted_instance.id) .build(); - let site = Site::create(conn, &site_form).await.unwrap(); + let site = Site::create(pool, &site_form).await.unwrap(); // Create a local site, since this is necessary for local languages let local_site_form = LocalSiteInsertForm::builder().site_id(site.id).build(); - LocalSite::create(conn, &local_site_form) - .await - .unwrap(); + LocalSite::create(pool, &local_site_form).await.unwrap(); (site, inserted_instance) } @@ -454,14 +469,15 @@ mod tests { #[tokio::test] #[serial] async fn test_convert_update_languages() { - let mut conn = build_db_conn_for_tests().await; + let pool = &build_db_pool_for_tests().await; // call with empty vec, returns all languages + let conn = &mut get_conn(pool).await.unwrap(); let converted1 = convert_update_languages(conn, vec![]).await.unwrap(); assert_eq!(184, converted1.len()); // call with nonempty vec, returns same vec - let test_langs = test_langs1(conn).await; + let test_langs = test_langs1(pool).await; let converted2 = convert_update_languages(conn, test_langs.clone()) .await .unwrap(); @@ -471,15 +487,16 @@ mod tests { #[serial] async fn test_convert_read_languages() { use crate::schema::language::dsl::{id, language}; - let mut conn = build_db_conn_for_tests().await; + let pool = &build_db_pool_for_tests().await; // call with all languages, returns empty vec + let conn = &mut get_conn(pool).await.unwrap(); let all_langs = language.select(id).get_results(conn).await.unwrap(); let converted1: Vec = convert_read_languages(conn, all_langs).await.unwrap(); assert_eq!(0, converted1.len()); // call with nonempty vec, returns same vec - let test_langs = test_langs1(conn).await; + let test_langs = test_langs1(pool).await; let converted2 = convert_read_languages(conn, test_langs.clone()) .await .unwrap(); @@ -489,35 +506,35 @@ mod tests { #[tokio::test] #[serial] async fn test_site_languages() { - let mut conn = build_db_conn_for_tests().await; + let pool = &build_db_pool_for_tests().await; - let (site, instance) = create_test_site(conn).await; - let site_languages1 = SiteLanguage::read_local_raw(conn).await.unwrap(); + let (site, instance) = create_test_site(pool).await; + let site_languages1 = SiteLanguage::read_local_raw(pool).await.unwrap(); // site is created with all languages assert_eq!(184, site_languages1.len()); - let test_langs = test_langs1(conn).await; - SiteLanguage::update(conn, test_langs.clone(), &site) + let test_langs = test_langs1(pool).await; + SiteLanguage::update(pool, test_langs.clone(), &site) .await .unwrap(); - let site_languages2 = SiteLanguage::read_local_raw(conn).await.unwrap(); + let site_languages2 = SiteLanguage::read_local_raw(pool).await.unwrap(); // after update, site only has new languages assert_eq!(test_langs, site_languages2); - Site::delete(conn, site.id).await.unwrap(); - Instance::delete(conn, instance.id).await.unwrap(); - LocalSite::delete(conn).await.unwrap(); + Site::delete(pool, site.id).await.unwrap(); + Instance::delete(pool, instance.id).await.unwrap(); + LocalSite::delete(pool).await.unwrap(); } #[tokio::test] #[serial] async fn test_user_languages() { - let mut conn = build_db_conn_for_tests().await; + let pool = &build_db_pool_for_tests().await; - let (site, instance) = create_test_site(conn).await; - let mut test_langs = test_langs1(conn).await; - SiteLanguage::update(conn, test_langs.clone(), &site) + let (site, instance) = create_test_site(pool).await; + let mut test_langs = test_langs1(pool).await; + SiteLanguage::update(pool, test_langs.clone(), &site) .await .unwrap(); @@ -526,18 +543,14 @@ mod tests { .public_key("pubkey".to_string()) .instance_id(instance.id) .build(); - let person = Person::create(conn, &person_form).await.unwrap(); + let person = Person::create(pool, &person_form).await.unwrap(); let local_user_form = LocalUserInsertForm::builder() .person_id(person.id) .password_encrypted("my_pw".to_string()) .build(); - let local_user = LocalUser::create(conn, &local_user_form) - .await - .unwrap(); - let local_user_langs1 = LocalUserLanguage::read(conn, local_user.id) - .await - .unwrap(); + let local_user = LocalUser::create(pool, &local_user_form).await.unwrap(); + let local_user_langs1 = LocalUserLanguage::read(pool, local_user.id).await.unwrap(); // new user should be initialized with site languages and undetermined //test_langs.push(UNDETERMINED_ID); @@ -546,37 +559,35 @@ mod tests { assert_eq!(test_langs, local_user_langs1); // update user languages - let test_langs2 = test_langs2(conn).await; - LocalUserLanguage::update(conn, test_langs2, local_user.id) - .await - .unwrap(); - let local_user_langs2 = LocalUserLanguage::read(conn, local_user.id) + let test_langs2 = test_langs2(pool).await; + LocalUserLanguage::update(pool, test_langs2, local_user.id) .await .unwrap(); + let local_user_langs2 = LocalUserLanguage::read(pool, local_user.id).await.unwrap(); assert_eq!(3, local_user_langs2.len()); - Person::delete(conn, person.id).await.unwrap(); - LocalUser::delete(conn, local_user.id).await.unwrap(); - Site::delete(conn, site.id).await.unwrap(); - LocalSite::delete(conn).await.unwrap(); - Instance::delete(conn, instance.id).await.unwrap(); + Person::delete(pool, person.id).await.unwrap(); + LocalUser::delete(pool, local_user.id).await.unwrap(); + Site::delete(pool, site.id).await.unwrap(); + LocalSite::delete(pool).await.unwrap(); + Instance::delete(pool, instance.id).await.unwrap(); } #[tokio::test] #[serial] async fn test_community_languages() { - let mut conn = build_db_conn_for_tests().await; - let (site, instance) = create_test_site(conn).await; - let test_langs = test_langs1(conn).await; - SiteLanguage::update(conn, test_langs.clone(), &site) + let pool = &build_db_pool_for_tests().await; + let (site, instance) = create_test_site(pool).await; + let test_langs = test_langs1(pool).await; + SiteLanguage::update(pool, test_langs.clone(), &site) .await .unwrap(); - let read_site_langs = SiteLanguage::read(conn, site.id).await.unwrap(); + let read_site_langs = SiteLanguage::read(pool, site.id).await.unwrap(); assert_eq!(test_langs, read_site_langs); // Test the local ones are the same - let read_local_site_langs = SiteLanguage::read_local_raw(conn).await.unwrap(); + let read_local_site_langs = SiteLanguage::read_local_raw(pool).await.unwrap(); assert_eq!(test_langs, read_local_site_langs); let community_form = CommunityInsertForm::builder() @@ -585,65 +596,51 @@ mod tests { .public_key("pubkey".to_string()) .instance_id(instance.id) .build(); - let community = Community::create(conn, &community_form) - .await - .unwrap(); - let community_langs1 = CommunityLanguage::read(conn, community.id) - .await - .unwrap(); + let community = Community::create(pool, &community_form).await.unwrap(); + let community_langs1 = CommunityLanguage::read(pool, community.id).await.unwrap(); // community is initialized with site languages assert_eq!(test_langs, community_langs1); - let allowed_lang1 = CommunityLanguage::is_allowed_community_language( - conn, - Some(test_langs[0]), - community.id, - ) - .await; + let allowed_lang1 = + CommunityLanguage::is_allowed_community_language(pool, Some(test_langs[0]), community.id) + .await; assert!(allowed_lang1.is_ok()); - let test_langs2 = test_langs2(conn).await; - let allowed_lang2 = CommunityLanguage::is_allowed_community_language( - conn, - Some(test_langs2[0]), - community.id, - ) - .await; + let test_langs2 = test_langs2(pool).await; + let allowed_lang2 = + CommunityLanguage::is_allowed_community_language(pool, Some(test_langs2[0]), community.id) + .await; assert!(allowed_lang2.is_err()); // limit site languages to en, fi. after this, community languages should be updated to // intersection of old languages (en, fr, ru) and (en, fi), which is only fi. - SiteLanguage::update(conn, vec![test_langs[0], test_langs2[0]], &site) - .await - .unwrap(); - let community_langs2 = CommunityLanguage::read(conn, community.id) + SiteLanguage::update(pool, vec![test_langs[0], test_langs2[0]], &site) .await .unwrap(); + let community_langs2 = CommunityLanguage::read(pool, community.id).await.unwrap(); assert_eq!(vec![test_langs[0]], community_langs2); // update community languages to different ones - CommunityLanguage::update(conn, test_langs2.clone(), community.id) - .await - .unwrap(); - let community_langs3 = CommunityLanguage::read(conn, community.id) + CommunityLanguage::update(pool, test_langs2.clone(), community.id) .await .unwrap(); + let community_langs3 = CommunityLanguage::read(pool, community.id).await.unwrap(); assert_eq!(test_langs2, community_langs3); - Community::delete(conn, community.id).await.unwrap(); - Site::delete(conn, site.id).await.unwrap(); - LocalSite::delete(conn).await.unwrap(); - Instance::delete(conn, instance.id).await.unwrap(); + Community::delete(pool, community.id).await.unwrap(); + Site::delete(pool, site.id).await.unwrap(); + LocalSite::delete(pool).await.unwrap(); + Instance::delete(pool, instance.id).await.unwrap(); } #[tokio::test] #[serial] async fn test_default_post_language() { - let mut conn = build_db_conn_for_tests().await; - let (site, instance) = create_test_site(conn).await; - let test_langs = test_langs1(conn).await; - let test_langs2 = test_langs2(conn).await; + let pool = &build_db_pool_for_tests().await; + let (site, instance) = create_test_site(pool).await; + let test_langs = test_langs1(pool).await; + let test_langs2 = test_langs2(pool).await; let community_form = CommunityInsertForm::builder() .name("test community".to_string()) @@ -651,10 +648,8 @@ mod tests { .public_key("pubkey".to_string()) .instance_id(instance.id) .build(); - let community = Community::create(conn, &community_form) - .await - .unwrap(); - CommunityLanguage::update(conn, test_langs, community.id) + let community = Community::create(pool, &community_form).await.unwrap(); + CommunityLanguage::update(pool, test_langs, community.id) .await .unwrap(); @@ -663,55 +658,53 @@ mod tests { .public_key("pubkey".to_string()) .instance_id(instance.id) .build(); - let person = Person::create(conn, &person_form).await.unwrap(); + let person = Person::create(pool, &person_form).await.unwrap(); let local_user_form = LocalUserInsertForm::builder() .person_id(person.id) .password_encrypted("my_pw".to_string()) .build(); - let local_user = LocalUser::create(conn, &local_user_form) - .await - .unwrap(); - LocalUserLanguage::update(conn, test_langs2, local_user.id) + let local_user = LocalUser::create(pool, &local_user_form).await.unwrap(); + LocalUserLanguage::update(pool, test_langs2, local_user.id) .await .unwrap(); // no overlap in user/community languages, so defaults to undetermined - let def1 = default_post_language(conn, community.id, local_user.id) + let def1 = default_post_language(pool, community.id, local_user.id) .await .unwrap(); assert_eq!(None, def1); - let ru = Language::read_id_from_code(conn, Some("ru")) + let ru = Language::read_id_from_code(pool, Some("ru")) .await .unwrap() .unwrap(); let test_langs3 = vec![ ru, - Language::read_id_from_code(conn, Some("fi")) + Language::read_id_from_code(pool, Some("fi")) .await .unwrap() .unwrap(), - Language::read_id_from_code(conn, Some("se")) + Language::read_id_from_code(pool, Some("se")) .await .unwrap() .unwrap(), UNDETERMINED_ID, ]; - LocalUserLanguage::update(conn, test_langs3, local_user.id) + LocalUserLanguage::update(pool, test_langs3, local_user.id) .await .unwrap(); // this time, both have ru as common lang - let def2 = default_post_language(conn, community.id, local_user.id) + let def2 = default_post_language(pool, community.id, local_user.id) .await .unwrap(); assert_eq!(Some(ru), def2); - Person::delete(conn, person.id).await.unwrap(); - Community::delete(conn, community.id).await.unwrap(); - LocalUser::delete(conn, local_user.id).await.unwrap(); - Site::delete(conn, site.id).await.unwrap(); - LocalSite::delete(conn).await.unwrap(); - Instance::delete(conn, instance.id).await.unwrap(); + Person::delete(pool, person.id).await.unwrap(); + Community::delete(pool, community.id).await.unwrap(); + LocalUser::delete(pool, local_user.id).await.unwrap(); + Site::delete(pool, site.id).await.unwrap(); + LocalSite::delete(pool).await.unwrap(); + Instance::delete(pool, instance.id).await.unwrap(); } } diff --git a/crates/db_schema/src/impls/captcha_answer.rs b/crates/db_schema/src/impls/captcha_answer.rs index 029de4b6c..de5fac65e 100644 --- a/crates/db_schema/src/impls/captcha_answer.rs +++ b/crates/db_schema/src/impls/captcha_answer.rs @@ -1,7 +1,7 @@ use crate::{ schema::captcha_answer::dsl::{answer, captcha_answer, uuid}, source::captcha_answer::{CaptchaAnswer, CaptchaAnswerForm, CheckCaptchaAnswer}, - utils::{functions::lower, GetConn}, + utils::{functions::lower, get_conn, DbPool}, }; use diesel::{ delete, @@ -12,20 +12,21 @@ use diesel::{ ExpressionMethods, QueryDsl, }; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::RunQueryDsl; impl CaptchaAnswer { - pub async fn insert(mut conn: impl GetConn, captcha: &CaptchaAnswerForm) -> Result { + pub async fn insert(pool: &DbPool, captcha: &CaptchaAnswerForm) -> Result { + let conn = &mut get_conn(pool).await?; + insert_into(captcha_answer) .values(captcha) .get_result::(conn) .await } - pub async fn check_captcha( - mut conn: impl GetConn, - to_check: CheckCaptchaAnswer, - ) -> Result { + pub async fn check_captcha(pool: &DbPool, to_check: CheckCaptchaAnswer) -> Result { + let conn = &mut get_conn(pool).await?; + // fetch requested captcha let captcha_exists = select(exists( captcha_answer @@ -48,17 +49,17 @@ impl CaptchaAnswer { mod tests { use crate::{ source::captcha_answer::{CaptchaAnswer, CaptchaAnswerForm, CheckCaptchaAnswer}, - utils::build_db_conn_for_tests, + utils::build_db_pool_for_tests, }; use serial_test::serial; #[tokio::test] #[serial] async fn test_captcha_happy_path() { - let mut conn = build_db_conn_for_tests().await; + let pool = &build_db_pool_for_tests().await; let inserted = CaptchaAnswer::insert( - conn, + pool, &CaptchaAnswerForm { answer: "XYZ".to_string(), }, @@ -67,7 +68,7 @@ mod tests { .expect("should not fail to insert captcha"); let result = CaptchaAnswer::check_captcha( - conn, + pool, CheckCaptchaAnswer { uuid: inserted.uuid, answer: "xyz".to_string(), @@ -82,10 +83,10 @@ mod tests { #[tokio::test] #[serial] async fn test_captcha_repeat_answer_fails() { - let mut conn = build_db_conn_for_tests().await; + let pool = &build_db_pool_for_tests().await; let inserted = CaptchaAnswer::insert( - conn, + pool, &CaptchaAnswerForm { answer: "XYZ".to_string(), }, @@ -94,7 +95,7 @@ mod tests { .expect("should not fail to insert captcha"); let _result = CaptchaAnswer::check_captcha( - conn, + pool, CheckCaptchaAnswer { uuid: inserted.uuid, answer: "xyz".to_string(), @@ -103,7 +104,7 @@ mod tests { .await; let result_repeat = CaptchaAnswer::check_captcha( - conn, + pool, CheckCaptchaAnswer { uuid: inserted.uuid, answer: "xyz".to_string(), diff --git a/crates/db_schema/src/impls/comment.rs b/crates/db_schema/src/impls/comment.rs index 932204450..ea66347db 100644 --- a/crates/db_schema/src/impls/comment.rs +++ b/crates/db_schema/src/impls/comment.rs @@ -11,7 +11,7 @@ use crate::{ CommentUpdateForm, }, traits::{Crud, Likeable, Saveable}, - utils::{naive_now, GetConn, DELETED_REPLACEMENT_TEXT}, + utils::{get_conn, naive_now, DbPool, DELETED_REPLACEMENT_TEXT}, }; use diesel::{ dsl::{insert_into, sql_query}, @@ -19,15 +19,17 @@ use diesel::{ ExpressionMethods, QueryDsl, }; +use diesel_async::RunQueryDsl; use diesel_ltree::Ltree; -use lemmy_db_schema::utils::RunQueryDsl; use url::Url; impl Comment { pub async fn permadelete_for_creator( - mut conn: impl GetConn, + pool: &DbPool, for_creator_id: PersonId, ) -> Result, Error> { + let conn = &mut get_conn(pool).await?; + diesel::update(comment.filter(creator_id.eq(for_creator_id))) .set(( content.eq(DELETED_REPLACEMENT_TEXT), @@ -39,10 +41,11 @@ impl Comment { } pub async fn update_removed_for_creator( - mut conn: impl GetConn, + pool: &DbPool, for_creator_id: PersonId, new_removed: bool, ) -> Result, Error> { + let conn = &mut get_conn(pool).await?; diesel::update(comment.filter(creator_id.eq(for_creator_id))) .set((removed.eq(new_removed), updated.eq(naive_now()))) .get_results::(conn) @@ -50,10 +53,12 @@ impl Comment { } pub async fn create( - mut conn: impl GetConn, + pool: &DbPool, comment_form: &CommentInsertForm, parent_path: Option<&Ltree>, ) -> Result { + let conn = &mut get_conn(pool).await?; + // Insert, to get the id let inserted_comment = insert_into(comment) .values(comment_form) @@ -110,9 +115,7 @@ from ( where ca.comment_id = c.id" ); - sql_query(update_child_count_stmt) - .execute(conn) - .await?; + sql_query(update_child_count_stmt).execute(conn).await?; } } updated_comment @@ -120,10 +123,8 @@ where ca.comment_id = c.id" inserted_comment } } - pub async fn read_from_apub_id( - mut conn: impl GetConn, - object_id: Url, - ) -> Result, Error> { + pub async fn read_from_apub_id(pool: &DbPool, object_id: Url) -> Result, Error> { + let conn = &mut get_conn(pool).await?; let object_id: DbUrl = object_id.into(); Ok( comment @@ -152,26 +153,27 @@ impl Crud for Comment { type InsertForm = CommentInsertForm; type UpdateForm = CommentUpdateForm; type IdType = CommentId; - async fn read(mut conn: impl GetConn, comment_id: CommentId) -> Result { + async fn read(pool: &DbPool, comment_id: CommentId) -> Result { + let conn = &mut get_conn(pool).await?; comment.find(comment_id).first::(conn).await } - async fn delete(mut conn: impl GetConn, comment_id: CommentId) -> Result { - diesel::delete(comment.find(comment_id)) - .execute(conn) - .await + async fn delete(pool: &DbPool, comment_id: CommentId) -> Result { + let conn = &mut get_conn(pool).await?; + diesel::delete(comment.find(comment_id)).execute(conn).await } /// This is unimplemented, use [[Comment::create]] - async fn create(_conn: impl GetConn, _comment_form: &Self::InsertForm) -> Result { + async fn create(_pool: &DbPool, _comment_form: &Self::InsertForm) -> Result { unimplemented!(); } async fn update( - mut conn: impl GetConn, + pool: &DbPool, comment_id: CommentId, comment_form: &Self::UpdateForm, ) -> Result { + let conn = &mut get_conn(pool).await?; diesel::update(comment.find(comment_id)) .set(comment_form) .get_result::(conn) @@ -183,11 +185,9 @@ impl Crud for Comment { impl Likeable for CommentLike { type Form = CommentLikeForm; type IdType = CommentId; - async fn like( - mut conn: impl GetConn, - comment_like_form: &CommentLikeForm, - ) -> Result { + async fn like(pool: &DbPool, comment_like_form: &CommentLikeForm) -> Result { use crate::schema::comment_like::dsl::{comment_id, comment_like, person_id}; + let conn = &mut get_conn(pool).await?; insert_into(comment_like) .values(comment_like_form) .on_conflict((comment_id, person_id)) @@ -197,11 +197,12 @@ impl Likeable for CommentLike { .await } async fn remove( - mut conn: impl GetConn, + pool: &DbPool, person_id_: PersonId, comment_id_: CommentId, ) -> Result { use crate::schema::comment_like::dsl::{comment_id, comment_like, person_id}; + let conn = &mut get_conn(pool).await?; diesel::delete( comment_like .filter(comment_id.eq(comment_id_)) @@ -215,11 +216,9 @@ impl Likeable for CommentLike { #[async_trait] impl Saveable for CommentSaved { type Form = CommentSavedForm; - async fn save( - mut conn: impl GetConn, - comment_saved_form: &CommentSavedForm, - ) -> Result { + async fn save(pool: &DbPool, comment_saved_form: &CommentSavedForm) -> Result { use crate::schema::comment_saved::dsl::{comment_id, comment_saved, person_id}; + let conn = &mut get_conn(pool).await?; insert_into(comment_saved) .values(comment_saved_form) .on_conflict((comment_id, person_id)) @@ -228,11 +227,9 @@ impl Saveable for CommentSaved { .get_result::(conn) .await } - async fn unsave( - mut conn: impl GetConn, - comment_saved_form: &CommentSavedForm, - ) -> Result { + async fn unsave(pool: &DbPool, comment_saved_form: &CommentSavedForm) -> Result { use crate::schema::comment_saved::dsl::{comment_id, comment_saved, person_id}; + let conn = &mut get_conn(pool).await?; diesel::delete( comment_saved .filter(comment_id.eq(comment_saved_form.comment_id)) @@ -263,7 +260,7 @@ mod tests { post::{Post, PostInsertForm}, }, traits::{Crud, Likeable, Saveable}, - utils::build_db_conn_for_tests, + utils::build_db_pool_for_tests, }; use diesel_ltree::Ltree; use serial_test::serial; @@ -271,9 +268,9 @@ mod tests { #[tokio::test] #[serial] async fn test_crud() { - let mut conn = build_db_conn_for_tests().await; + let pool = &build_db_pool_for_tests().await; - let inserted_instance = Instance::read_or_create(conn, "my_domain.tld".to_string()) + let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()) .await .unwrap(); @@ -283,7 +280,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_person = Person::create(conn, &new_person).await.unwrap(); + let inserted_person = Person::create(pool, &new_person).await.unwrap(); let new_community = CommunityInsertForm::builder() .name("test community".to_string()) @@ -292,7 +289,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_community = Community::create(conn, &new_community).await.unwrap(); + let inserted_community = Community::create(pool, &new_community).await.unwrap(); let new_post = PostInsertForm::builder() .name("A test post".into()) @@ -300,7 +297,7 @@ mod tests { .community_id(inserted_community.id) .build(); - let inserted_post = Post::create(conn, &new_post).await.unwrap(); + let inserted_post = Post::create(pool, &new_post).await.unwrap(); let comment_form = CommentInsertForm::builder() .content("A test comment".into()) @@ -308,9 +305,7 @@ mod tests { .post_id(inserted_post.id) .build(); - let inserted_comment = Comment::create(conn, &comment_form, None) - .await - .unwrap(); + let inserted_comment = Comment::create(pool, &comment_form, None).await.unwrap(); let expected_comment = Comment { id: inserted_comment.id, @@ -334,13 +329,10 @@ mod tests { .post_id(inserted_post.id) .build(); - let inserted_child_comment = Comment::create( - conn, - &child_comment_form, - Some(&inserted_comment.path), - ) - .await - .unwrap(); + let inserted_child_comment = + Comment::create(pool, &child_comment_form, Some(&inserted_comment.path)) + .await + .unwrap(); // Comment Like let comment_like_form = CommentLikeForm { @@ -350,9 +342,7 @@ mod tests { score: 1, }; - let inserted_comment_like = CommentLike::like(conn, &comment_like_form) - .await - .unwrap(); + let inserted_comment_like = CommentLike::like(pool, &comment_like_form).await.unwrap(); let expected_comment_like = CommentLike { id: inserted_comment_like.id, @@ -369,9 +359,7 @@ mod tests { person_id: inserted_person.id, }; - let inserted_comment_saved = CommentSaved::save(conn, &comment_saved_form) - .await - .unwrap(); + let inserted_comment_saved = CommentSaved::save(pool, &comment_saved_form).await.unwrap(); let expected_comment_saved = CommentSaved { id: inserted_comment_saved.id, @@ -384,35 +372,27 @@ mod tests { .content(Some("A test comment".into())) .build(); - let updated_comment = Comment::update(conn, inserted_comment.id, &comment_update_form) + let updated_comment = Comment::update(pool, inserted_comment.id, &comment_update_form) .await .unwrap(); - let read_comment = Comment::read(conn, inserted_comment.id) + let read_comment = Comment::read(pool, inserted_comment.id).await.unwrap(); + let like_removed = CommentLike::remove(pool, inserted_person.id, inserted_comment.id) .await .unwrap(); - let like_removed = CommentLike::remove(conn, inserted_person.id, inserted_comment.id) + let saved_removed = CommentSaved::unsave(pool, &comment_saved_form) .await .unwrap(); - let saved_removed = CommentSaved::unsave(conn, &comment_saved_form) + let num_deleted = Comment::delete(pool, inserted_comment.id).await.unwrap(); + Comment::delete(pool, inserted_child_comment.id) .await .unwrap(); - let num_deleted = Comment::delete(conn, inserted_comment.id) - .await - .unwrap(); - Comment::delete(conn, inserted_child_comment.id) - .await - .unwrap(); - Post::delete(conn, inserted_post.id).await.unwrap(); - Community::delete(conn, inserted_community.id) - .await - .unwrap(); - Person::delete(conn, inserted_person.id) - .await - .unwrap(); - Instance::delete(conn, inserted_instance.id) + Post::delete(pool, inserted_post.id).await.unwrap(); + Community::delete(pool, inserted_community.id) .await .unwrap(); + Person::delete(pool, inserted_person.id).await.unwrap(); + Instance::delete(pool, inserted_instance.id).await.unwrap(); assert_eq!(expected_comment, read_comment); assert_eq!(expected_comment, inserted_comment); diff --git a/crates/db_schema/src/impls/comment_reply.rs b/crates/db_schema/src/impls/comment_reply.rs index 7efca02e6..2489c982f 100644 --- a/crates/db_schema/src/impls/comment_reply.rs +++ b/crates/db_schema/src/impls/comment_reply.rs @@ -3,27 +3,27 @@ use crate::{ schema::comment_reply::dsl::{comment_id, comment_reply, read, recipient_id}, source::comment_reply::{CommentReply, CommentReplyInsertForm, CommentReplyUpdateForm}, traits::Crud, - utils::GetConn, + utils::{get_conn, DbPool}, }; use diesel::{dsl::insert_into, result::Error, ExpressionMethods, QueryDsl}; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::RunQueryDsl; #[async_trait] impl Crud for CommentReply { type InsertForm = CommentReplyInsertForm; type UpdateForm = CommentReplyUpdateForm; type IdType = CommentReplyId; - async fn read(mut conn: impl GetConn, comment_reply_id: CommentReplyId) -> Result { + async fn read(pool: &DbPool, comment_reply_id: CommentReplyId) -> Result { + let conn = &mut get_conn(pool).await?; comment_reply .find(comment_reply_id) .first::(conn) .await } - async fn create( - mut conn: impl GetConn, - comment_reply_form: &Self::InsertForm, - ) -> Result { + async fn create(pool: &DbPool, comment_reply_form: &Self::InsertForm) -> Result { + let conn = &mut get_conn(pool).await?; + // since the return here isnt utilized, we dont need to do an update // but get_result doesnt return the existing row here insert_into(comment_reply) @@ -36,10 +36,11 @@ impl Crud for CommentReply { } async fn update( - mut conn: impl GetConn, + pool: &DbPool, comment_reply_id: CommentReplyId, comment_reply_form: &Self::UpdateForm, ) -> Result { + let conn = &mut get_conn(pool).await?; diesel::update(comment_reply.find(comment_reply_id)) .set(comment_reply_form) .get_result::(conn) @@ -49,9 +50,10 @@ impl Crud for CommentReply { impl CommentReply { pub async fn mark_all_as_read( - mut conn: impl GetConn, + pool: &DbPool, for_recipient_id: PersonId, ) -> Result, Error> { + let conn = &mut get_conn(pool).await?; diesel::update( comment_reply .filter(recipient_id.eq(for_recipient_id)) @@ -62,10 +64,8 @@ impl CommentReply { .await } - pub async fn read_by_comment( - mut conn: impl GetConn, - for_comment_id: CommentId, - ) -> Result { + pub async fn read_by_comment(pool: &DbPool, for_comment_id: CommentId) -> Result { + let conn = &mut get_conn(pool).await?; comment_reply .filter(comment_id.eq(for_comment_id)) .first::(conn) @@ -85,16 +85,16 @@ mod tests { post::{Post, PostInsertForm}, }, traits::Crud, - utils::build_db_conn_for_tests, + utils::build_db_pool_for_tests, }; use serial_test::serial; #[tokio::test] #[serial] async fn test_crud() { - let mut conn = build_db_conn_for_tests().await; + let pool = &build_db_pool_for_tests().await; - let inserted_instance = Instance::read_or_create(conn, "my_domain.tld".to_string()) + let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()) .await .unwrap(); @@ -104,7 +104,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_person = Person::create(conn, &new_person).await.unwrap(); + let inserted_person = Person::create(pool, &new_person).await.unwrap(); let recipient_form = PersonInsertForm::builder() .name("terrylakes recipient".into()) @@ -112,7 +112,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_recipient = Person::create(conn, &recipient_form).await.unwrap(); + let inserted_recipient = Person::create(pool, &recipient_form).await.unwrap(); let new_community = CommunityInsertForm::builder() .name("test community lake".to_string()) @@ -121,7 +121,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_community = Community::create(conn, &new_community).await.unwrap(); + let inserted_community = Community::create(pool, &new_community).await.unwrap(); let new_post = PostInsertForm::builder() .name("A test post".into()) @@ -129,7 +129,7 @@ mod tests { .community_id(inserted_community.id) .build(); - let inserted_post = Post::create(conn, &new_post).await.unwrap(); + let inserted_post = Post::create(pool, &new_post).await.unwrap(); let comment_form = CommentInsertForm::builder() .content("A test comment".into()) @@ -137,9 +137,7 @@ mod tests { .post_id(inserted_post.id) .build(); - let inserted_comment = Comment::create(conn, &comment_form, None) - .await - .unwrap(); + let inserted_comment = Comment::create(pool, &comment_form, None).await.unwrap(); let comment_reply_form = CommentReplyInsertForm { recipient_id: inserted_recipient.id, @@ -147,7 +145,7 @@ mod tests { read: None, }; - let inserted_reply = CommentReply::create(conn, &comment_reply_form) + let inserted_reply = CommentReply::create(pool, &comment_reply_form) .await .unwrap(); @@ -159,32 +157,21 @@ mod tests { published: inserted_reply.published, }; - let read_reply = CommentReply::read(conn, inserted_reply.id) - .await - .unwrap(); + let read_reply = CommentReply::read(pool, inserted_reply.id).await.unwrap(); let comment_reply_update_form = CommentReplyUpdateForm { read: Some(false) }; - let updated_reply = - CommentReply::update(conn, inserted_reply.id, &comment_reply_update_form) - .await - .unwrap(); + let updated_reply = CommentReply::update(pool, inserted_reply.id, &comment_reply_update_form) + .await + .unwrap(); - Comment::delete(conn, inserted_comment.id) - .await - .unwrap(); - Post::delete(conn, inserted_post.id).await.unwrap(); - Community::delete(conn, inserted_community.id) - .await - .unwrap(); - Person::delete(conn, inserted_person.id) - .await - .unwrap(); - Person::delete(conn, inserted_recipient.id) - .await - .unwrap(); - Instance::delete(conn, inserted_instance.id) + Comment::delete(pool, inserted_comment.id).await.unwrap(); + Post::delete(pool, inserted_post.id).await.unwrap(); + Community::delete(pool, inserted_community.id) .await .unwrap(); + Person::delete(pool, inserted_person.id).await.unwrap(); + Person::delete(pool, inserted_recipient.id).await.unwrap(); + Instance::delete(pool, inserted_instance.id).await.unwrap(); assert_eq!(expected_reply, read_reply); assert_eq!(expected_reply, inserted_reply); diff --git a/crates/db_schema/src/impls/comment_report.rs b/crates/db_schema/src/impls/comment_report.rs index 3bf8dad49..18cf83a72 100644 --- a/crates/db_schema/src/impls/comment_report.rs +++ b/crates/db_schema/src/impls/comment_report.rs @@ -3,7 +3,7 @@ use crate::{ schema::comment_report::dsl::{comment_report, resolved, resolver_id, updated}, source::comment_report::{CommentReport, CommentReportForm}, traits::Reportable, - utils::{naive_now, GetConn}, + utils::{get_conn, naive_now, DbPool}, }; use diesel::{ dsl::{insert_into, update}, @@ -11,7 +11,7 @@ use diesel::{ ExpressionMethods, QueryDsl, }; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::RunQueryDsl; #[async_trait] impl Reportable for CommentReport { @@ -21,10 +21,8 @@ impl Reportable for CommentReport { /// /// * `conn` - the postgres connection /// * `comment_report_form` - the filled CommentReportForm to insert - async fn report( - mut conn: impl GetConn, - comment_report_form: &CommentReportForm, - ) -> Result { + async fn report(pool: &DbPool, comment_report_form: &CommentReportForm) -> Result { + let conn = &mut get_conn(pool).await?; insert_into(comment_report) .values(comment_report_form) .get_result::(conn) @@ -37,10 +35,11 @@ impl Reportable for CommentReport { /// * `report_id` - the id of the report to resolve /// * `by_resolver_id` - the id of the user resolving the report async fn resolve( - mut conn: impl GetConn, + pool: &DbPool, report_id_: Self::IdType, by_resolver_id: PersonId, ) -> Result { + let conn = &mut get_conn(pool).await?; update(comment_report.find(report_id_)) .set(( resolved.eq(true), @@ -57,10 +56,11 @@ impl Reportable for CommentReport { /// * `report_id` - the id of the report to unresolve /// * `by_resolver_id` - the id of the user unresolving the report async fn unresolve( - mut conn: impl GetConn, + pool: &DbPool, report_id_: Self::IdType, by_resolver_id: PersonId, ) -> Result { + let conn = &mut get_conn(pool).await?; update(comment_report.find(report_id_)) .set(( resolved.eq(false), diff --git a/crates/db_schema/src/impls/community.rs b/crates/db_schema/src/impls/community.rs index d7040434a..ad9e6d47d 100644 --- a/crates/db_schema/src/impls/community.rs +++ b/crates/db_schema/src/impls/community.rs @@ -16,35 +16,36 @@ use crate::{ }, }, traits::{ApubActor, Bannable, Crud, Followable, Joinable}, - utils::{functions::lower, GetConn}, + utils::{functions::lower, get_conn, DbPool}, SubscribedType, }; use diesel::{dsl::insert_into, result::Error, ExpressionMethods, QueryDsl}; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::RunQueryDsl; #[async_trait] impl Crud for Community { type InsertForm = CommunityInsertForm; type UpdateForm = CommunityUpdateForm; type IdType = CommunityId; - async fn read(mut conn: impl GetConn, community_id: CommunityId) -> Result { + async fn read(pool: &DbPool, community_id: CommunityId) -> Result { + let conn = &mut get_conn(pool).await?; community::table .find(community_id) .first::(conn) .await } - async fn delete(mut conn: impl GetConn, community_id: CommunityId) -> Result { + async fn delete(pool: &DbPool, community_id: CommunityId) -> Result { + let conn = &mut get_conn(pool).await?; diesel::delete(community::table.find(community_id)) .execute(conn) .await } - async fn create(mut conn: impl GetConn, form: &Self::InsertForm) -> Result { + async fn create(pool: &DbPool, form: &Self::InsertForm) -> Result { + let conn = &mut get_conn(pool).await?; let is_new_community = match &form.actor_id { - Some(id) => Community::read_from_apub_id(conn, id) - .await? - .is_none(), + Some(id) => Community::read_from_apub_id(pool, id).await?.is_none(), None => true, }; @@ -59,17 +60,18 @@ impl Crud for Community { // Initialize languages for new community if is_new_community { - CommunityLanguage::update(conn, vec![], community_.id).await?; + CommunityLanguage::update(pool, vec![], community_.id).await?; } Ok(community_) } async fn update( - mut conn: impl GetConn, + pool: &DbPool, community_id: CommunityId, form: &Self::UpdateForm, ) -> Result { + let conn = &mut get_conn(pool).await?; diesel::update(community::table.find(community_id)) .set(form) .get_result::(conn) @@ -81,10 +83,11 @@ impl Crud for Community { impl Joinable for CommunityModerator { type Form = CommunityModeratorForm; async fn join( - mut conn: impl GetConn, + pool: &DbPool, community_moderator_form: &CommunityModeratorForm, ) -> Result { use crate::schema::community_moderator::dsl::community_moderator; + let conn = &mut get_conn(pool).await?; insert_into(community_moderator) .values(community_moderator_form) .get_result::(conn) @@ -92,10 +95,11 @@ impl Joinable for CommunityModerator { } async fn leave( - mut conn: impl GetConn, + pool: &DbPool, community_moderator_form: &CommunityModeratorForm, ) -> Result { use crate::schema::community_moderator::dsl::{community_id, community_moderator, person_id}; + let conn = &mut get_conn(pool).await?; diesel::delete( community_moderator .filter(community_id.eq(community_moderator_form.community_id)) @@ -114,11 +118,12 @@ pub enum CollectionType { impl Community { /// Get the community which has a given moderators or featured url, also return the collection type pub async fn get_by_collection_url( - mut conn: impl GetConn, + pool: &DbPool, url: &DbUrl, ) -> Result<(Community, CollectionType), Error> { use crate::schema::community::dsl::{featured_url, moderators_url}; use CollectionType::*; + let conn = &mut get_conn(pool).await?; let res = community::table .filter(moderators_url.eq(url)) .first::(conn) @@ -139,10 +144,11 @@ impl Community { impl CommunityModerator { pub async fn delete_for_community( - mut conn: impl GetConn, + pool: &DbPool, for_community_id: CommunityId, ) -> Result { use crate::schema::community_moderator::dsl::{community_id, community_moderator}; + let conn = &mut get_conn(pool).await?; diesel::delete(community_moderator.filter(community_id.eq(for_community_id))) .execute(conn) @@ -150,20 +156,22 @@ impl CommunityModerator { } pub async fn leave_all_communities( - mut conn: impl GetConn, + pool: &DbPool, for_person_id: PersonId, ) -> Result { use crate::schema::community_moderator::dsl::{community_moderator, person_id}; + let conn = &mut get_conn(pool).await?; diesel::delete(community_moderator.filter(person_id.eq(for_person_id))) .execute(conn) .await } pub async fn get_person_moderated_communities( - mut conn: impl GetConn, + pool: &DbPool, for_person_id: PersonId, ) -> Result, Error> { use crate::schema::community_moderator::dsl::{community_id, community_moderator, person_id}; + let conn = &mut get_conn(pool).await?; community_moderator .filter(person_id.eq(for_person_id)) .select(community_id) @@ -176,10 +184,11 @@ impl CommunityModerator { impl Bannable for CommunityPersonBan { type Form = CommunityPersonBanForm; async fn ban( - mut conn: impl GetConn, + pool: &DbPool, community_person_ban_form: &CommunityPersonBanForm, ) -> Result { use crate::schema::community_person_ban::dsl::{community_id, community_person_ban, person_id}; + let conn = &mut get_conn(pool).await?; insert_into(community_person_ban) .values(community_person_ban_form) .on_conflict((community_id, person_id)) @@ -190,10 +199,11 @@ impl Bannable for CommunityPersonBan { } async fn unban( - mut conn: impl GetConn, + pool: &DbPool, community_person_ban_form: &CommunityPersonBanForm, ) -> Result { use crate::schema::community_person_ban::dsl::{community_id, community_person_ban, person_id}; + let conn = &mut get_conn(pool).await?; diesel::delete( community_person_ban .filter(community_id.eq(community_person_ban_form.community_id)) @@ -223,8 +233,9 @@ impl CommunityFollower { #[async_trait] impl Followable for CommunityFollower { type Form = CommunityFollowerForm; - async fn follow(mut conn: impl GetConn, form: &CommunityFollowerForm) -> Result { + async fn follow(pool: &DbPool, form: &CommunityFollowerForm) -> Result { use crate::schema::community_follower::dsl::{community_follower, community_id, person_id}; + let conn = &mut get_conn(pool).await?; insert_into(community_follower) .values(form) .on_conflict((community_id, person_id)) @@ -234,7 +245,7 @@ impl Followable for CommunityFollower { .await } async fn follow_accepted( - mut conn: impl GetConn, + pool: &DbPool, community_id_: CommunityId, person_id_: PersonId, ) -> Result { @@ -244,6 +255,7 @@ impl Followable for CommunityFollower { pending, person_id, }; + let conn = &mut get_conn(pool).await?; diesel::update( community_follower .filter(community_id.eq(community_id_)) @@ -253,8 +265,9 @@ impl Followable for CommunityFollower { .get_result::(conn) .await } - async fn unfollow(mut conn: impl GetConn, form: &CommunityFollowerForm) -> Result { + async fn unfollow(pool: &DbPool, form: &CommunityFollowerForm) -> Result { use crate::schema::community_follower::dsl::{community_follower, community_id, person_id}; + let conn = &mut get_conn(pool).await?; diesel::delete( community_follower .filter(community_id.eq(&form.community_id)) @@ -267,10 +280,8 @@ impl Followable for CommunityFollower { #[async_trait] impl ApubActor for Community { - async fn read_from_apub_id( - mut conn: impl GetConn, - object_id: &DbUrl, - ) -> Result, Error> { + async fn read_from_apub_id(pool: &DbPool, object_id: &DbUrl) -> Result, Error> { + let conn = &mut get_conn(pool).await?; Ok( community::table .filter(community::actor_id.eq(object_id)) @@ -282,10 +293,11 @@ impl ApubActor for Community { } async fn read_from_name( - mut conn: impl GetConn, + pool: &DbPool, community_name: &str, include_deleted: bool, ) -> Result { + let conn = &mut get_conn(pool).await?; let mut q = community::table .into_boxed() .filter(community::local.eq(true)) @@ -299,10 +311,11 @@ impl ApubActor for Community { } async fn read_from_name_and_domain( - mut conn: impl GetConn, + pool: &DbPool, community_name: &str, for_domain: &str, ) -> Result { + let conn = &mut get_conn(pool).await?; community::table .inner_join(instance::table) .filter(lower(community::name).eq(community_name.to_lowercase())) @@ -332,16 +345,16 @@ mod tests { person::{Person, PersonInsertForm}, }, traits::{Bannable, Crud, Followable, Joinable}, - utils::build_db_conn_for_tests, + utils::build_db_pool_for_tests, }; use serial_test::serial; #[tokio::test] #[serial] async fn test_crud() { - let mut conn = build_db_conn_for_tests().await; + let pool = &build_db_pool_for_tests().await; - let inserted_instance = Instance::read_or_create(conn, "my_domain.tld".to_string()) + let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()) .await .unwrap(); @@ -351,7 +364,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_person = Person::create(conn, &new_person).await.unwrap(); + let inserted_person = Person::create(pool, &new_person).await.unwrap(); let new_community = CommunityInsertForm::builder() .name("TIL".into()) @@ -360,7 +373,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_community = Community::create(conn, &new_community).await.unwrap(); + let inserted_community = Community::create(pool, &new_community).await.unwrap(); let expected_community = Community { id: inserted_community.id, @@ -395,10 +408,9 @@ mod tests { pending: false, }; - let inserted_community_follower = - CommunityFollower::follow(conn, &community_follower_form) - .await - .unwrap(); + let inserted_community_follower = CommunityFollower::follow(pool, &community_follower_form) + .await + .unwrap(); let expected_community_follower = CommunityFollower { id: inserted_community_follower.id, @@ -413,10 +425,9 @@ mod tests { person_id: inserted_person.id, }; - let inserted_community_moderator = - CommunityModerator::join(conn, &community_moderator_form) - .await - .unwrap(); + let inserted_community_moderator = CommunityModerator::join(pool, &community_moderator_form) + .await + .unwrap(); let expected_community_moderator = CommunityModerator { id: inserted_community_moderator.id, @@ -431,10 +442,9 @@ mod tests { expires: None, }; - let inserted_community_person_ban = - CommunityPersonBan::ban(conn, &community_person_ban_form) - .await - .unwrap(); + let inserted_community_person_ban = CommunityPersonBan::ban(pool, &community_person_ban_form) + .await + .unwrap(); let expected_community_person_ban = CommunityPersonBan { id: inserted_community_person_ban.id, @@ -444,36 +454,29 @@ mod tests { expires: None, }; - let read_community = Community::read(conn, inserted_community.id) - .await - .unwrap(); + let read_community = Community::read(pool, inserted_community.id).await.unwrap(); let update_community_form = CommunityUpdateForm::builder() .title(Some("nada".to_owned())) .build(); - let updated_community = - Community::update(conn, inserted_community.id, &update_community_form) - .await - .unwrap(); + let updated_community = Community::update(pool, inserted_community.id, &update_community_form) + .await + .unwrap(); - let ignored_community = CommunityFollower::unfollow(conn, &community_follower_form) + let ignored_community = CommunityFollower::unfollow(pool, &community_follower_form) .await .unwrap(); - let left_community = CommunityModerator::leave(conn, &community_moderator_form) + let left_community = CommunityModerator::leave(pool, &community_moderator_form) .await .unwrap(); - let unban = CommunityPersonBan::unban(conn, &community_person_ban_form) + let unban = CommunityPersonBan::unban(pool, &community_person_ban_form) .await .unwrap(); - let num_deleted = Community::delete(conn, inserted_community.id) - .await - .unwrap(); - Person::delete(conn, inserted_person.id) - .await - .unwrap(); - Instance::delete(conn, inserted_instance.id) + let num_deleted = Community::delete(pool, inserted_community.id) .await .unwrap(); + Person::delete(pool, inserted_person.id).await.unwrap(); + Instance::delete(pool, inserted_instance.id).await.unwrap(); assert_eq!(expected_community, read_community); assert_eq!(expected_community, inserted_community); diff --git a/crates/db_schema/src/impls/community_block.rs b/crates/db_schema/src/impls/community_block.rs index 4e1fdf9a2..c1f35e625 100644 --- a/crates/db_schema/src/impls/community_block.rs +++ b/crates/db_schema/src/impls/community_block.rs @@ -2,15 +2,16 @@ use crate::{ schema::community_block::dsl::{community_block, community_id, person_id}, source::community_block::{CommunityBlock, CommunityBlockForm}, traits::Blockable, - utils::GetConn, + utils::{get_conn, DbPool}, }; use diesel::{dsl::insert_into, result::Error, ExpressionMethods, QueryDsl}; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::RunQueryDsl; #[async_trait] impl Blockable for CommunityBlock { type Form = CommunityBlockForm; - async fn block(mut conn: impl GetConn, community_block_form: &Self::Form) -> Result { + async fn block(pool: &DbPool, community_block_form: &Self::Form) -> Result { + let conn = &mut get_conn(pool).await?; insert_into(community_block) .values(community_block_form) .on_conflict((person_id, community_id)) @@ -19,10 +20,8 @@ impl Blockable for CommunityBlock { .get_result::(conn) .await } - async fn unblock( - mut conn: impl GetConn, - community_block_form: &Self::Form, - ) -> Result { + async fn unblock(pool: &DbPool, community_block_form: &Self::Form) -> Result { + let conn = &mut get_conn(pool).await?; diesel::delete( community_block .filter(person_id.eq(community_block_form.person_id)) diff --git a/crates/db_schema/src/impls/custom_emoji.rs b/crates/db_schema/src/impls/custom_emoji.rs index ba54c2ed4..cce35dfc7 100644 --- a/crates/db_schema/src/impls/custom_emoji.rs +++ b/crates/db_schema/src/impls/custom_emoji.rs @@ -8,29 +8,32 @@ use crate::{ custom_emoji::{CustomEmoji, CustomEmojiInsertForm, CustomEmojiUpdateForm}, custom_emoji_keyword::{CustomEmojiKeyword, CustomEmojiKeywordInsertForm}, }, - utils::GetConn, + utils::{get_conn, DbPool}, }; use diesel::{dsl::insert_into, result::Error, ExpressionMethods, QueryDsl}; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::RunQueryDsl; impl CustomEmoji { - pub async fn create(mut conn: impl GetConn, form: &CustomEmojiInsertForm) -> Result { + pub async fn create(pool: &DbPool, form: &CustomEmojiInsertForm) -> Result { + let conn = &mut get_conn(pool).await?; insert_into(custom_emoji) .values(form) .get_result::(conn) .await } pub async fn update( - mut conn: impl GetConn, + pool: &DbPool, emoji_id: CustomEmojiId, form: &CustomEmojiUpdateForm, ) -> Result { + let conn = &mut get_conn(pool).await?; diesel::update(custom_emoji.find(emoji_id)) .set(form) .get_result::(conn) .await } - pub async fn delete(mut conn: impl GetConn, emoji_id: CustomEmojiId) -> Result { + pub async fn delete(pool: &DbPool, emoji_id: CustomEmojiId) -> Result { + let conn = &mut get_conn(pool).await?; diesel::delete(custom_emoji.find(emoji_id)) .execute(conn) .await @@ -39,15 +42,17 @@ impl CustomEmoji { impl CustomEmojiKeyword { pub async fn create( - mut conn: impl GetConn, + pool: &DbPool, form: Vec, ) -> Result, Error> { + let conn = &mut get_conn(pool).await?; insert_into(custom_emoji_keyword) .values(form) .get_results::(conn) .await } - pub async fn delete(mut conn: impl GetConn, emoji_id: CustomEmojiId) -> Result { + pub async fn delete(pool: &DbPool, emoji_id: CustomEmojiId) -> Result { + let conn = &mut get_conn(pool).await?; diesel::delete(custom_emoji_keyword.filter(custom_emoji_id.eq(emoji_id))) .execute(conn) .await diff --git a/crates/db_schema/src/impls/email_verification.rs b/crates/db_schema/src/impls/email_verification.rs index 968625ab0..af19bbba0 100644 --- a/crates/db_schema/src/impls/email_verification.rs +++ b/crates/db_schema/src/impls/email_verification.rs @@ -7,7 +7,7 @@ use crate::{ verification_token, }, source::email_verification::{EmailVerification, EmailVerificationForm}, - utils::GetConn, + utils::{get_conn, DbPool}, }; use diesel::{ dsl::{now, IntervalDsl}, @@ -16,17 +16,19 @@ use diesel::{ ExpressionMethods, QueryDsl, }; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::RunQueryDsl; impl EmailVerification { - pub async fn create(mut conn: impl GetConn, form: &EmailVerificationForm) -> Result { + pub async fn create(pool: &DbPool, form: &EmailVerificationForm) -> Result { + let conn = &mut get_conn(pool).await?; insert_into(email_verification) .values(form) .get_result::(conn) .await } - pub async fn read_for_token(mut conn: impl GetConn, token: &str) -> Result { + pub async fn read_for_token(pool: &DbPool, token: &str) -> Result { + let conn = &mut get_conn(pool).await?; email_verification .filter(verification_token.eq(token)) .filter(published.gt(now - 7.days())) @@ -34,9 +36,10 @@ impl EmailVerification { .await } pub async fn delete_old_tokens_for_local_user( - mut conn: impl GetConn, + pool: &DbPool, local_user_id_: LocalUserId, ) -> Result { + let conn = &mut get_conn(pool).await?; diesel::delete(email_verification.filter(local_user_id.eq(local_user_id_))) .execute(conn) .await diff --git a/crates/db_schema/src/impls/federation_allowlist.rs b/crates/db_schema/src/impls/federation_allowlist.rs index c5c4a8aff..c71ffd1cf 100644 --- a/crates/db_schema/src/impls/federation_allowlist.rs +++ b/crates/db_schema/src/impls/federation_allowlist.rs @@ -4,13 +4,14 @@ use crate::{ federation_allowlist::{FederationAllowList, FederationAllowListForm}, instance::Instance, }, - utils::GetConn, + utils::{get_conn, DbPool}, }; use diesel::{dsl::insert_into, result::Error}; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::{AsyncPgConnection, RunQueryDsl}; impl FederationAllowList { - pub async fn replace(mut conn: impl GetConn, list_opt: Option>) -> Result<(), Error> { + pub async fn replace(pool: &DbPool, list_opt: Option>) -> Result<(), Error> { + let conn = &mut get_conn(pool).await?; conn .build_transaction() .run(|conn| { @@ -40,7 +41,7 @@ impl FederationAllowList { .await } - async fn clear(mut conn: impl GetConn) -> Result { + async fn clear(conn: &mut AsyncPgConnection) -> Result { diesel::delete(federation_allowlist::table) .execute(conn) .await @@ -50,14 +51,14 @@ impl FederationAllowList { mod tests { use crate::{ source::{federation_allowlist::FederationAllowList, instance::Instance}, - utils::build_db_conn_for_tests, + utils::build_db_pool_for_tests, }; use serial_test::serial; #[tokio::test] #[serial] async fn test_allowlist_insert_and_clear() { - let mut conn = build_db_conn_for_tests().await; + let pool = &build_db_pool_for_tests().await; let domains = vec![ "tld1.xyz".to_string(), "tld2.xyz".to_string(), @@ -66,11 +67,9 @@ mod tests { let allowed = Some(domains.clone()); - FederationAllowList::replace(conn, allowed) - .await - .unwrap(); + FederationAllowList::replace(pool, allowed).await.unwrap(); - let allows = Instance::allowlist(conn).await.unwrap(); + let allows = Instance::allowlist(pool).await.unwrap(); let allows_domains = allows .iter() .map(|i| i.domain.clone()) @@ -82,13 +81,13 @@ mod tests { // Now test clearing them via Some(empty vec) let clear_allows = Some(Vec::new()); - FederationAllowList::replace(conn, clear_allows) + FederationAllowList::replace(pool, clear_allows) .await .unwrap(); - let allows = Instance::allowlist(conn).await.unwrap(); + let allows = Instance::allowlist(pool).await.unwrap(); assert_eq!(0, allows.len()); - Instance::delete_all(conn).await.unwrap(); + Instance::delete_all(pool).await.unwrap(); } } diff --git a/crates/db_schema/src/impls/federation_blocklist.rs b/crates/db_schema/src/impls/federation_blocklist.rs index 4ababd427..917bf57a3 100644 --- a/crates/db_schema/src/impls/federation_blocklist.rs +++ b/crates/db_schema/src/impls/federation_blocklist.rs @@ -4,13 +4,14 @@ use crate::{ federation_blocklist::{FederationBlockList, FederationBlockListForm}, instance::Instance, }, - utils::GetConn, + utils::{get_conn, DbPool}, }; use diesel::{dsl::insert_into, result::Error}; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::{AsyncPgConnection, RunQueryDsl}; impl FederationBlockList { - pub async fn replace(mut conn: impl GetConn, list_opt: Option>) -> Result<(), Error> { + pub async fn replace(pool: &DbPool, list_opt: Option>) -> Result<(), Error> { + let conn = &mut get_conn(pool).await?; conn .build_transaction() .run(|conn| { @@ -40,7 +41,7 @@ impl FederationBlockList { .await } - async fn clear(mut conn: impl GetConn) -> Result { + async fn clear(conn: &mut AsyncPgConnection) -> Result { diesel::delete(federation_blocklist::table) .execute(conn) .await diff --git a/crates/db_schema/src/impls/instance.rs b/crates/db_schema/src/impls/instance.rs index c8a90fdba..e5a8caba3 100644 --- a/crates/db_schema/src/impls/instance.rs +++ b/crates/db_schema/src/impls/instance.rs @@ -2,14 +2,14 @@ use crate::{ newtypes::InstanceId, schema::{federation_allowlist, federation_blocklist, instance}, source::instance::{Instance, InstanceForm}, - utils::{naive_now, GetConn}, + utils::{get_conn, naive_now, DbPool}, }; use diesel::{dsl::insert_into, result::Error, ExpressionMethods, QueryDsl}; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::{AsyncPgConnection, RunQueryDsl}; impl Instance { pub(crate) async fn read_or_create_with_conn( - mut conn: impl GetConn, + conn: &mut AsyncPgConnection, domain_: String, ) -> Result { use crate::schema::instance::domain; @@ -42,19 +42,23 @@ impl Instance { /// Attempt to read Instance column for the given domain. If it doesnt exist, insert a new one. /// There is no need for update as the domain of an existing instance cant change. - pub async fn read_or_create(mut conn: impl GetConn, domain: String) -> Result { + pub async fn read_or_create(pool: &DbPool, domain: String) -> Result { + let conn = &mut get_conn(pool).await?; Self::read_or_create_with_conn(conn, domain).await } - pub async fn delete(mut conn: impl GetConn, instance_id: InstanceId) -> Result { + pub async fn delete(pool: &DbPool, instance_id: InstanceId) -> Result { + let conn = &mut get_conn(pool).await?; diesel::delete(instance::table.find(instance_id)) .execute(conn) .await } #[cfg(test)] - pub async fn delete_all(mut conn: impl GetConn) -> Result { + pub async fn delete_all(pool: &DbPool) -> Result { + let conn = &mut get_conn(pool).await?; diesel::delete(instance::table).execute(conn).await } - pub async fn allowlist(mut conn: impl GetConn) -> Result, Error> { + pub async fn allowlist(pool: &DbPool) -> Result, Error> { + let conn = &mut get_conn(pool).await?; instance::table .inner_join(federation_allowlist::table) .select(instance::all_columns) @@ -62,7 +66,8 @@ impl Instance { .await } - pub async fn blocklist(mut conn: impl GetConn) -> Result, Error> { + pub async fn blocklist(pool: &DbPool) -> Result, Error> { + let conn = &mut get_conn(pool).await?; instance::table .inner_join(federation_blocklist::table) .select(instance::all_columns) @@ -70,7 +75,8 @@ impl Instance { .await } - pub async fn linked(mut conn: impl GetConn) -> Result, Error> { + pub async fn linked(pool: &DbPool) -> Result, Error> { + let conn = &mut get_conn(pool).await?; instance::table .left_join(federation_blocklist::table) .filter(federation_blocklist::id.is_null()) diff --git a/crates/db_schema/src/impls/language.rs b/crates/db_schema/src/impls/language.rs index f786b97ed..da9e0ca9d 100644 --- a/crates/db_schema/src/impls/language.rs +++ b/crates/db_schema/src/impls/language.rs @@ -3,30 +3,33 @@ use crate::{ newtypes::LanguageId, schema::language::dsl::{code, id, language}, source::language::Language, - utils::GetConn, + utils::{get_conn, DbPool}, }; use diesel::{result::Error, QueryDsl}; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::{AsyncPgConnection, RunQueryDsl}; impl Language { - pub async fn read_all(mut conn: impl GetConn) -> Result, Error> { + pub async fn read_all(pool: &DbPool) -> Result, Error> { + let conn = &mut get_conn(pool).await?; Self::read_all_conn(conn).await } - pub async fn read_all_conn(mut conn: impl GetConn) -> Result, Error> { + pub async fn read_all_conn(conn: &mut AsyncPgConnection) -> Result, Error> { language.load::(conn).await } - pub async fn read_from_id(mut conn: impl GetConn, id_: LanguageId) -> Result { + pub async fn read_from_id(pool: &DbPool, id_: LanguageId) -> Result { + let conn = &mut get_conn(pool).await?; language.filter(id.eq(id_)).first::(conn).await } /// Attempts to find the given language code and return its ID. If not found, returns none. pub async fn read_id_from_code( - mut conn: impl GetConn, + pool: &DbPool, code_: Option<&str>, ) -> Result, Error> { if let Some(code_) = code_ { + let conn = &mut get_conn(pool).await?; Ok( language .filter(code.eq(code_)) @@ -43,15 +46,15 @@ impl Language { #[cfg(test)] mod tests { - use crate::{source::language::Language, utils::build_db_conn_for_tests}; + use crate::{source::language::Language, utils::build_db_pool_for_tests}; use serial_test::serial; #[tokio::test] #[serial] async fn test_languages() { - let mut conn = build_db_conn_for_tests().await; + let pool = &build_db_pool_for_tests().await; - let all = Language::read_all(conn).await.unwrap(); + let all = Language::read_all(pool).await.unwrap(); assert_eq!(184, all.len()); assert_eq!("ak", all[5].code); diff --git a/crates/db_schema/src/impls/local_site.rs b/crates/db_schema/src/impls/local_site.rs index 5ffa9a23b..b9e920d15 100644 --- a/crates/db_schema/src/impls/local_site.rs +++ b/crates/db_schema/src/impls/local_site.rs @@ -1,28 +1,32 @@ use crate::{ schema::local_site::dsl::local_site, source::local_site::{LocalSite, LocalSiteInsertForm, LocalSiteUpdateForm}, - utils::GetConn, + utils::{get_conn, DbPool}, }; use diesel::{dsl::insert_into, result::Error}; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::RunQueryDsl; impl LocalSite { - pub async fn create(mut conn: impl GetConn, form: &LocalSiteInsertForm) -> Result { + pub async fn create(pool: &DbPool, form: &LocalSiteInsertForm) -> Result { + let conn = &mut get_conn(pool).await?; insert_into(local_site) .values(form) .get_result::(conn) .await } - pub async fn read(mut conn: impl GetConn) -> Result { + pub async fn read(pool: &DbPool) -> Result { + let conn = &mut get_conn(pool).await?; local_site.first::(conn).await } - pub async fn update(mut conn: impl GetConn, form: &LocalSiteUpdateForm) -> Result { + pub async fn update(pool: &DbPool, form: &LocalSiteUpdateForm) -> Result { + let conn = &mut get_conn(pool).await?; diesel::update(local_site) .set(form) .get_result::(conn) .await } - pub async fn delete(mut conn: impl GetConn) -> Result { + pub async fn delete(pool: &DbPool) -> Result { + let conn = &mut get_conn(pool).await?; diesel::delete(local_site).execute(conn).await } } diff --git a/crates/db_schema/src/impls/local_site_rate_limit.rs b/crates/db_schema/src/impls/local_site_rate_limit.rs index e7326cddd..b1af5f869 100644 --- a/crates/db_schema/src/impls/local_site_rate_limit.rs +++ b/crates/db_schema/src/impls/local_site_rate_limit.rs @@ -5,33 +5,30 @@ use crate::{ LocalSiteRateLimitInsertForm, LocalSiteRateLimitUpdateForm, }, - utils::GetConn, + utils::{get_conn, DbPool}, }; use diesel::{dsl::insert_into, result::Error}; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::RunQueryDsl; impl LocalSiteRateLimit { - pub async fn read(mut conn: impl GetConn) -> Result { + pub async fn read(pool: &DbPool) -> Result { + let conn = &mut get_conn(pool).await?; local_site_rate_limit::table.first::(conn).await } - pub async fn create( - mut conn: impl GetConn, - form: &LocalSiteRateLimitInsertForm, - ) -> Result { + pub async fn create(pool: &DbPool, form: &LocalSiteRateLimitInsertForm) -> Result { + let conn = &mut get_conn(pool).await?; insert_into(local_site_rate_limit::table) .values(form) .get_result::(conn) .await } - pub async fn update( - mut conn: impl GetConn, - form: &LocalSiteRateLimitUpdateForm, - ) -> Result<(), Error> { + pub async fn update(pool: &DbPool, form: &LocalSiteRateLimitUpdateForm) -> Result<(), Error> { // avoid error "There are no changes to save. This query cannot be built" if form.is_empty() { return Ok(()); } + let conn = &mut get_conn(pool).await?; diesel::update(local_site_rate_limit::table) .set(form) .get_result::(conn) diff --git a/crates/db_schema/src/impls/local_user.rs b/crates/db_schema/src/impls/local_user.rs index 46312914b..c8ae23627 100644 --- a/crates/db_schema/src/impls/local_user.rs +++ b/crates/db_schema/src/impls/local_user.rs @@ -13,18 +13,19 @@ use crate::{ local_user::{LocalUser, LocalUserInsertForm, LocalUserUpdateForm}, }, traits::Crud, - utils::{naive_now, GetConn}, + utils::{get_conn, naive_now, DbPool}, }; use bcrypt::{hash, DEFAULT_COST}; use diesel::{dsl::insert_into, result::Error, ExpressionMethods, QueryDsl}; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::RunQueryDsl; impl LocalUser { pub async fn update_password( - mut conn: impl GetConn, + pool: &DbPool, local_user_id: LocalUserId, new_password: &str, ) -> Result { + let conn = &mut get_conn(pool).await?; let password_hash = hash(new_password, DEFAULT_COST).expect("Couldn't hash password"); diesel::update(local_user.find(local_user_id)) @@ -36,7 +37,8 @@ impl LocalUser { .await } - pub async fn set_all_users_email_verified(mut conn: impl GetConn) -> Result, Error> { + pub async fn set_all_users_email_verified(pool: &DbPool) -> Result, Error> { + let conn = &mut get_conn(pool).await?; diesel::update(local_user) .set(email_verified.eq(true)) .get_results::(conn) @@ -44,16 +46,18 @@ impl LocalUser { } pub async fn set_all_users_registration_applications_accepted( - mut conn: impl GetConn, + pool: &DbPool, ) -> Result, Error> { + let conn = &mut get_conn(pool).await?; diesel::update(local_user) .set(accepted_application.eq(true)) .get_results::(conn) .await } - pub async fn is_email_taken(mut conn: impl GetConn, email_: &str) -> Result { + pub async fn is_email_taken(pool: &DbPool, email_: &str) -> Result { use diesel::dsl::{exists, select}; + let conn = &mut get_conn(pool).await?; select(exists(local_user.filter(email.eq(email_)))) .get_result(conn) .await @@ -65,18 +69,18 @@ impl Crud for LocalUser { type InsertForm = LocalUserInsertForm; type UpdateForm = LocalUserUpdateForm; type IdType = LocalUserId; - async fn read(mut conn: impl GetConn, local_user_id: LocalUserId) -> Result { - local_user - .find(local_user_id) - .first::(conn) - .await + async fn read(pool: &DbPool, local_user_id: LocalUserId) -> Result { + let conn = &mut get_conn(pool).await?; + local_user.find(local_user_id).first::(conn).await } - async fn delete(mut conn: impl GetConn, local_user_id: LocalUserId) -> Result { + async fn delete(pool: &DbPool, local_user_id: LocalUserId) -> Result { + let conn = &mut get_conn(pool).await?; diesel::delete(local_user.find(local_user_id)) .execute(conn) .await } - async fn create(mut conn: impl GetConn, form: &Self::InsertForm) -> Result { + async fn create(pool: &DbPool, form: &Self::InsertForm) -> Result { + let conn = &mut get_conn(pool).await?; let mut form_with_encrypted_password = form.clone(); let password_hash = hash(&form.password_encrypted, DEFAULT_COST).expect("Couldn't hash password"); @@ -87,23 +91,24 @@ impl Crud for LocalUser { .get_result::(conn) .await?; - let site_languages = SiteLanguage::read_local_raw(conn).await; + let site_languages = SiteLanguage::read_local_raw(pool).await; if let Ok(langs) = site_languages { // if site exists, init user with site languages - LocalUserLanguage::update(conn, langs, local_user_.id).await?; + LocalUserLanguage::update(pool, langs, local_user_.id).await?; } else { // otherwise, init with all languages (this only happens during tests and // for first admin user, which is created before site) - LocalUserLanguage::update(conn, vec![], local_user_.id).await?; + LocalUserLanguage::update(pool, vec![], local_user_.id).await?; } Ok(local_user_) } async fn update( - mut conn: impl GetConn, + pool: &DbPool, local_user_id: LocalUserId, form: &Self::UpdateForm, ) -> Result { + let conn = &mut get_conn(pool).await?; diesel::update(local_user.find(local_user_id)) .set(form) .get_result::(conn) diff --git a/crates/db_schema/src/impls/moderator.rs b/crates/db_schema/src/impls/moderator.rs index c636967a8..ab8398cf3 100644 --- a/crates/db_schema/src/impls/moderator.rs +++ b/crates/db_schema/src/impls/moderator.rs @@ -32,38 +32,34 @@ use crate::{ ModTransferCommunityForm, }, traits::Crud, - utils::GetConn, + utils::{get_conn, DbPool}, }; use diesel::{dsl::insert_into, result::Error, QueryDsl}; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::RunQueryDsl; #[async_trait] impl Crud for ModRemovePost { type InsertForm = ModRemovePostForm; type UpdateForm = ModRemovePostForm; type IdType = i32; - async fn read(mut conn: impl GetConn, from_id: i32) -> Result { + async fn read(pool: &DbPool, from_id: i32) -> Result { use crate::schema::mod_remove_post::dsl::mod_remove_post; - mod_remove_post - .find(from_id) - .first::(conn) - .await + let conn = &mut get_conn(pool).await?; + mod_remove_post.find(from_id).first::(conn).await } - async fn create(mut conn: impl GetConn, form: &ModRemovePostForm) -> Result { + async fn create(pool: &DbPool, form: &ModRemovePostForm) -> Result { use crate::schema::mod_remove_post::dsl::mod_remove_post; + let conn = &mut get_conn(pool).await?; insert_into(mod_remove_post) .values(form) .get_result::(conn) .await } - async fn update( - mut conn: impl GetConn, - from_id: i32, - form: &ModRemovePostForm, - ) -> Result { + async fn update(pool: &DbPool, from_id: i32, form: &ModRemovePostForm) -> Result { use crate::schema::mod_remove_post::dsl::mod_remove_post; + let conn = &mut get_conn(pool).await?; diesel::update(mod_remove_post.find(from_id)) .set(form) .get_result::(conn) @@ -76,25 +72,24 @@ impl Crud for ModLockPost { type InsertForm = ModLockPostForm; type UpdateForm = ModLockPostForm; type IdType = i32; - async fn read(mut conn: impl GetConn, from_id: i32) -> Result { + async fn read(pool: &DbPool, from_id: i32) -> Result { use crate::schema::mod_lock_post::dsl::mod_lock_post; + let conn = &mut get_conn(pool).await?; mod_lock_post.find(from_id).first::(conn).await } - async fn create(mut conn: impl GetConn, form: &ModLockPostForm) -> Result { + async fn create(pool: &DbPool, form: &ModLockPostForm) -> Result { use crate::schema::mod_lock_post::dsl::mod_lock_post; + let conn = &mut get_conn(pool).await?; insert_into(mod_lock_post) .values(form) .get_result::(conn) .await } - async fn update( - mut conn: impl GetConn, - from_id: i32, - form: &ModLockPostForm, - ) -> Result { + async fn update(pool: &DbPool, from_id: i32, form: &ModLockPostForm) -> Result { use crate::schema::mod_lock_post::dsl::mod_lock_post; + let conn = &mut get_conn(pool).await?; diesel::update(mod_lock_post.find(from_id)) .set(form) .get_result::(conn) @@ -107,28 +102,24 @@ impl Crud for ModFeaturePost { type InsertForm = ModFeaturePostForm; type UpdateForm = ModFeaturePostForm; type IdType = i32; - async fn read(mut conn: impl GetConn, from_id: i32) -> Result { + async fn read(pool: &DbPool, from_id: i32) -> Result { use crate::schema::mod_feature_post::dsl::mod_feature_post; - mod_feature_post - .find(from_id) - .first::(conn) - .await + let conn = &mut get_conn(pool).await?; + mod_feature_post.find(from_id).first::(conn).await } - async fn create(mut conn: impl GetConn, form: &ModFeaturePostForm) -> Result { + async fn create(pool: &DbPool, form: &ModFeaturePostForm) -> Result { use crate::schema::mod_feature_post::dsl::mod_feature_post; + let conn = &mut get_conn(pool).await?; insert_into(mod_feature_post) .values(form) .get_result::(conn) .await } - async fn update( - mut conn: impl GetConn, - from_id: i32, - form: &ModFeaturePostForm, - ) -> Result { + async fn update(pool: &DbPool, from_id: i32, form: &ModFeaturePostForm) -> Result { use crate::schema::mod_feature_post::dsl::mod_feature_post; + let conn = &mut get_conn(pool).await?; diesel::update(mod_feature_post.find(from_id)) .set(form) .get_result::(conn) @@ -141,28 +132,24 @@ impl Crud for ModRemoveComment { type InsertForm = ModRemoveCommentForm; type UpdateForm = ModRemoveCommentForm; type IdType = i32; - async fn read(mut conn: impl GetConn, from_id: i32) -> Result { + async fn read(pool: &DbPool, from_id: i32) -> Result { use crate::schema::mod_remove_comment::dsl::mod_remove_comment; - mod_remove_comment - .find(from_id) - .first::(conn) - .await + let conn = &mut get_conn(pool).await?; + mod_remove_comment.find(from_id).first::(conn).await } - async fn create(mut conn: impl GetConn, form: &ModRemoveCommentForm) -> Result { + async fn create(pool: &DbPool, form: &ModRemoveCommentForm) -> Result { use crate::schema::mod_remove_comment::dsl::mod_remove_comment; + let conn = &mut get_conn(pool).await?; insert_into(mod_remove_comment) .values(form) .get_result::(conn) .await } - async fn update( - mut conn: impl GetConn, - from_id: i32, - form: &ModRemoveCommentForm, - ) -> Result { + async fn update(pool: &DbPool, from_id: i32, form: &ModRemoveCommentForm) -> Result { use crate::schema::mod_remove_comment::dsl::mod_remove_comment; + let conn = &mut get_conn(pool).await?; diesel::update(mod_remove_comment.find(from_id)) .set(form) .get_result::(conn) @@ -175,16 +162,15 @@ impl Crud for ModRemoveCommunity { type InsertForm = ModRemoveCommunityForm; type UpdateForm = ModRemoveCommunityForm; type IdType = i32; - async fn read(mut conn: impl GetConn, from_id: i32) -> Result { + async fn read(pool: &DbPool, from_id: i32) -> Result { use crate::schema::mod_remove_community::dsl::mod_remove_community; - mod_remove_community - .find(from_id) - .first::(conn) - .await + let conn = &mut get_conn(pool).await?; + mod_remove_community.find(from_id).first::(conn).await } - async fn create(mut conn: impl GetConn, form: &ModRemoveCommunityForm) -> Result { + async fn create(pool: &DbPool, form: &ModRemoveCommunityForm) -> Result { use crate::schema::mod_remove_community::dsl::mod_remove_community; + let conn = &mut get_conn(pool).await?; insert_into(mod_remove_community) .values(form) .get_result::(conn) @@ -192,11 +178,12 @@ impl Crud for ModRemoveCommunity { } async fn update( - mut conn: impl GetConn, + pool: &DbPool, from_id: i32, form: &ModRemoveCommunityForm, ) -> Result { use crate::schema::mod_remove_community::dsl::mod_remove_community; + let conn = &mut get_conn(pool).await?; diesel::update(mod_remove_community.find(from_id)) .set(form) .get_result::(conn) @@ -209,16 +196,18 @@ impl Crud for ModBanFromCommunity { type InsertForm = ModBanFromCommunityForm; type UpdateForm = ModBanFromCommunityForm; type IdType = i32; - async fn read(mut conn: impl GetConn, from_id: i32) -> Result { + async fn read(pool: &DbPool, from_id: i32) -> Result { use crate::schema::mod_ban_from_community::dsl::mod_ban_from_community; + let conn = &mut get_conn(pool).await?; mod_ban_from_community .find(from_id) .first::(conn) .await } - async fn create(mut conn: impl GetConn, form: &ModBanFromCommunityForm) -> Result { + async fn create(pool: &DbPool, form: &ModBanFromCommunityForm) -> Result { use crate::schema::mod_ban_from_community::dsl::mod_ban_from_community; + let conn = &mut get_conn(pool).await?; insert_into(mod_ban_from_community) .values(form) .get_result::(conn) @@ -226,11 +215,12 @@ impl Crud for ModBanFromCommunity { } async fn update( - mut conn: impl GetConn, + pool: &DbPool, from_id: i32, form: &ModBanFromCommunityForm, ) -> Result { use crate::schema::mod_ban_from_community::dsl::mod_ban_from_community; + let conn = &mut get_conn(pool).await?; diesel::update(mod_ban_from_community.find(from_id)) .set(form) .get_result::(conn) @@ -243,21 +233,24 @@ impl Crud for ModBan { type InsertForm = ModBanForm; type UpdateForm = ModBanForm; type IdType = i32; - async fn read(mut conn: impl GetConn, from_id: i32) -> Result { + async fn read(pool: &DbPool, from_id: i32) -> Result { use crate::schema::mod_ban::dsl::mod_ban; + let conn = &mut get_conn(pool).await?; mod_ban.find(from_id).first::(conn).await } - async fn create(mut conn: impl GetConn, form: &ModBanForm) -> Result { + async fn create(pool: &DbPool, form: &ModBanForm) -> Result { use crate::schema::mod_ban::dsl::mod_ban; + let conn = &mut get_conn(pool).await?; insert_into(mod_ban) .values(form) .get_result::(conn) .await } - async fn update(mut conn: impl GetConn, from_id: i32, form: &ModBanForm) -> Result { + async fn update(pool: &DbPool, from_id: i32, form: &ModBanForm) -> Result { use crate::schema::mod_ban::dsl::mod_ban; + let conn = &mut get_conn(pool).await?; diesel::update(mod_ban.find(from_id)) .set(form) .get_result::(conn) @@ -271,28 +264,24 @@ impl Crud for ModHideCommunity { type UpdateForm = ModHideCommunityForm; type IdType = i32; - async fn read(mut conn: impl GetConn, from_id: i32) -> Result { + async fn read(pool: &DbPool, from_id: i32) -> Result { use crate::schema::mod_hide_community::dsl::mod_hide_community; - mod_hide_community - .find(from_id) - .first::(conn) - .await + let conn = &mut get_conn(pool).await?; + mod_hide_community.find(from_id).first::(conn).await } - async fn create(mut conn: impl GetConn, form: &ModHideCommunityForm) -> Result { + async fn create(pool: &DbPool, form: &ModHideCommunityForm) -> Result { use crate::schema::mod_hide_community::dsl::mod_hide_community; + let conn = &mut get_conn(pool).await?; insert_into(mod_hide_community) .values(form) .get_result::(conn) .await } - async fn update( - mut conn: impl GetConn, - from_id: i32, - form: &ModHideCommunityForm, - ) -> Result { + async fn update(pool: &DbPool, from_id: i32, form: &ModHideCommunityForm) -> Result { use crate::schema::mod_hide_community::dsl::mod_hide_community; + let conn = &mut get_conn(pool).await?; diesel::update(mod_hide_community.find(from_id)) .set(form) .get_result::(conn) @@ -305,28 +294,24 @@ impl Crud for ModAddCommunity { type InsertForm = ModAddCommunityForm; type UpdateForm = ModAddCommunityForm; type IdType = i32; - async fn read(mut conn: impl GetConn, from_id: i32) -> Result { + async fn read(pool: &DbPool, from_id: i32) -> Result { use crate::schema::mod_add_community::dsl::mod_add_community; - mod_add_community - .find(from_id) - .first::(conn) - .await + let conn = &mut get_conn(pool).await?; + mod_add_community.find(from_id).first::(conn).await } - async fn create(mut conn: impl GetConn, form: &ModAddCommunityForm) -> Result { + async fn create(pool: &DbPool, form: &ModAddCommunityForm) -> Result { use crate::schema::mod_add_community::dsl::mod_add_community; + let conn = &mut get_conn(pool).await?; insert_into(mod_add_community) .values(form) .get_result::(conn) .await } - async fn update( - mut conn: impl GetConn, - from_id: i32, - form: &ModAddCommunityForm, - ) -> Result { + async fn update(pool: &DbPool, from_id: i32, form: &ModAddCommunityForm) -> Result { use crate::schema::mod_add_community::dsl::mod_add_community; + let conn = &mut get_conn(pool).await?; diesel::update(mod_add_community.find(from_id)) .set(form) .get_result::(conn) @@ -339,16 +324,18 @@ impl Crud for ModTransferCommunity { type InsertForm = ModTransferCommunityForm; type UpdateForm = ModTransferCommunityForm; type IdType = i32; - async fn read(mut conn: impl GetConn, from_id: i32) -> Result { + async fn read(pool: &DbPool, from_id: i32) -> Result { use crate::schema::mod_transfer_community::dsl::mod_transfer_community; + let conn = &mut get_conn(pool).await?; mod_transfer_community .find(from_id) .first::(conn) .await } - async fn create(mut conn: impl GetConn, form: &ModTransferCommunityForm) -> Result { + async fn create(pool: &DbPool, form: &ModTransferCommunityForm) -> Result { use crate::schema::mod_transfer_community::dsl::mod_transfer_community; + let conn = &mut get_conn(pool).await?; insert_into(mod_transfer_community) .values(form) .get_result::(conn) @@ -356,11 +343,12 @@ impl Crud for ModTransferCommunity { } async fn update( - mut conn: impl GetConn, + pool: &DbPool, from_id: i32, form: &ModTransferCommunityForm, ) -> Result { use crate::schema::mod_transfer_community::dsl::mod_transfer_community; + let conn = &mut get_conn(pool).await?; diesel::update(mod_transfer_community.find(from_id)) .set(form) .get_result::(conn) @@ -373,21 +361,24 @@ impl Crud for ModAdd { type InsertForm = ModAddForm; type UpdateForm = ModAddForm; type IdType = i32; - async fn read(mut conn: impl GetConn, from_id: i32) -> Result { + async fn read(pool: &DbPool, from_id: i32) -> Result { use crate::schema::mod_add::dsl::mod_add; + let conn = &mut get_conn(pool).await?; mod_add.find(from_id).first::(conn).await } - async fn create(mut conn: impl GetConn, form: &ModAddForm) -> Result { + async fn create(pool: &DbPool, form: &ModAddForm) -> Result { use crate::schema::mod_add::dsl::mod_add; + let conn = &mut get_conn(pool).await?; insert_into(mod_add) .values(form) .get_result::(conn) .await } - async fn update(mut conn: impl GetConn, from_id: i32, form: &ModAddForm) -> Result { + async fn update(pool: &DbPool, from_id: i32, form: &ModAddForm) -> Result { use crate::schema::mod_add::dsl::mod_add; + let conn = &mut get_conn(pool).await?; diesel::update(mod_add.find(from_id)) .set(form) .get_result::(conn) @@ -400,28 +391,24 @@ impl Crud for AdminPurgePerson { type InsertForm = AdminPurgePersonForm; type UpdateForm = AdminPurgePersonForm; type IdType = i32; - async fn read(mut conn: impl GetConn, from_id: i32) -> Result { + async fn read(pool: &DbPool, from_id: i32) -> Result { use crate::schema::admin_purge_person::dsl::admin_purge_person; - admin_purge_person - .find(from_id) - .first::(conn) - .await + let conn = &mut get_conn(pool).await?; + admin_purge_person.find(from_id).first::(conn).await } - async fn create(mut conn: impl GetConn, form: &Self::InsertForm) -> Result { + async fn create(pool: &DbPool, form: &Self::InsertForm) -> Result { use crate::schema::admin_purge_person::dsl::admin_purge_person; + let conn = &mut get_conn(pool).await?; insert_into(admin_purge_person) .values(form) .get_result::(conn) .await } - async fn update( - mut conn: impl GetConn, - from_id: i32, - form: &Self::InsertForm, - ) -> Result { + async fn update(pool: &DbPool, from_id: i32, form: &Self::InsertForm) -> Result { use crate::schema::admin_purge_person::dsl::admin_purge_person; + let conn = &mut get_conn(pool).await?; diesel::update(admin_purge_person.find(from_id)) .set(form) .get_result::(conn) @@ -434,28 +421,27 @@ impl Crud for AdminPurgeCommunity { type InsertForm = AdminPurgeCommunityForm; type UpdateForm = AdminPurgeCommunityForm; type IdType = i32; - async fn read(mut conn: impl GetConn, from_id: i32) -> Result { + async fn read(pool: &DbPool, from_id: i32) -> Result { use crate::schema::admin_purge_community::dsl::admin_purge_community; + let conn = &mut get_conn(pool).await?; admin_purge_community .find(from_id) .first::(conn) .await } - async fn create(mut conn: impl GetConn, form: &Self::InsertForm) -> Result { + async fn create(pool: &DbPool, form: &Self::InsertForm) -> Result { use crate::schema::admin_purge_community::dsl::admin_purge_community; + let conn = &mut get_conn(pool).await?; insert_into(admin_purge_community) .values(form) .get_result::(conn) .await } - async fn update( - mut conn: impl GetConn, - from_id: i32, - form: &Self::InsertForm, - ) -> Result { + async fn update(pool: &DbPool, from_id: i32, form: &Self::InsertForm) -> Result { use crate::schema::admin_purge_community::dsl::admin_purge_community; + let conn = &mut get_conn(pool).await?; diesel::update(admin_purge_community.find(from_id)) .set(form) .get_result::(conn) @@ -468,28 +454,24 @@ impl Crud for AdminPurgePost { type InsertForm = AdminPurgePostForm; type UpdateForm = AdminPurgePostForm; type IdType = i32; - async fn read(mut conn: impl GetConn, from_id: i32) -> Result { + async fn read(pool: &DbPool, from_id: i32) -> Result { use crate::schema::admin_purge_post::dsl::admin_purge_post; - admin_purge_post - .find(from_id) - .first::(conn) - .await + let conn = &mut get_conn(pool).await?; + admin_purge_post.find(from_id).first::(conn).await } - async fn create(mut conn: impl GetConn, form: &Self::InsertForm) -> Result { + async fn create(pool: &DbPool, form: &Self::InsertForm) -> Result { use crate::schema::admin_purge_post::dsl::admin_purge_post; + let conn = &mut get_conn(pool).await?; insert_into(admin_purge_post) .values(form) .get_result::(conn) .await } - async fn update( - mut conn: impl GetConn, - from_id: i32, - form: &Self::InsertForm, - ) -> Result { + async fn update(pool: &DbPool, from_id: i32, form: &Self::InsertForm) -> Result { use crate::schema::admin_purge_post::dsl::admin_purge_post; + let conn = &mut get_conn(pool).await?; diesel::update(admin_purge_post.find(from_id)) .set(form) .get_result::(conn) @@ -502,28 +484,24 @@ impl Crud for AdminPurgeComment { type InsertForm = AdminPurgeCommentForm; type UpdateForm = AdminPurgeCommentForm; type IdType = i32; - async fn read(mut conn: impl GetConn, from_id: i32) -> Result { + async fn read(pool: &DbPool, from_id: i32) -> Result { use crate::schema::admin_purge_comment::dsl::admin_purge_comment; - admin_purge_comment - .find(from_id) - .first::(conn) - .await + let conn = &mut get_conn(pool).await?; + admin_purge_comment.find(from_id).first::(conn).await } - async fn create(mut conn: impl GetConn, form: &Self::InsertForm) -> Result { + async fn create(pool: &DbPool, form: &Self::InsertForm) -> Result { use crate::schema::admin_purge_comment::dsl::admin_purge_comment; + let conn = &mut get_conn(pool).await?; insert_into(admin_purge_comment) .values(form) .get_result::(conn) .await } - async fn update( - mut conn: impl GetConn, - from_id: i32, - form: &Self::InsertForm, - ) -> Result { + async fn update(pool: &DbPool, from_id: i32, form: &Self::InsertForm) -> Result { use crate::schema::admin_purge_comment::dsl::admin_purge_comment; + let conn = &mut get_conn(pool).await?; diesel::update(admin_purge_comment.find(from_id)) .set(form) .get_result::(conn) @@ -562,16 +540,16 @@ mod tests { post::{Post, PostInsertForm}, }, traits::Crud, - utils::build_db_conn_for_tests, + utils::build_db_pool_for_tests, }; use serial_test::serial; #[tokio::test] #[serial] async fn test_crud() { - let mut conn = build_db_conn_for_tests().await; + let pool = &build_db_pool_for_tests().await; - let inserted_instance = Instance::read_or_create(conn, "my_domain.tld".to_string()) + let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()) .await .unwrap(); @@ -581,7 +559,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_mod = Person::create(conn, &new_mod).await.unwrap(); + let inserted_mod = Person::create(pool, &new_mod).await.unwrap(); let new_person = PersonInsertForm::builder() .name("jim2".into()) @@ -589,7 +567,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_person = Person::create(conn, &new_person).await.unwrap(); + let inserted_person = Person::create(pool, &new_person).await.unwrap(); let new_community = CommunityInsertForm::builder() .name("mod_community".to_string()) @@ -598,7 +576,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_community = Community::create(conn, &new_community).await.unwrap(); + let inserted_community = Community::create(pool, &new_community).await.unwrap(); let new_post = PostInsertForm::builder() .name("A test post thweep".into()) @@ -606,7 +584,7 @@ mod tests { .community_id(inserted_community.id) .build(); - let inserted_post = Post::create(conn, &new_post).await.unwrap(); + let inserted_post = Post::create(pool, &new_post).await.unwrap(); let comment_form = CommentInsertForm::builder() .content("A test comment".into()) @@ -614,9 +592,7 @@ mod tests { .post_id(inserted_post.id) .build(); - let inserted_comment = Comment::create(conn, &comment_form, None) - .await - .unwrap(); + let inserted_comment = Comment::create(pool, &comment_form, None).await.unwrap(); // Now the actual tests @@ -627,10 +603,10 @@ mod tests { reason: None, removed: None, }; - let inserted_mod_remove_post = ModRemovePost::create(conn, &mod_remove_post_form) + let inserted_mod_remove_post = ModRemovePost::create(pool, &mod_remove_post_form) .await .unwrap(); - let read_mod_remove_post = ModRemovePost::read(conn, inserted_mod_remove_post.id) + let read_mod_remove_post = ModRemovePost::read(pool, inserted_mod_remove_post.id) .await .unwrap(); let expected_mod_remove_post = ModRemovePost { @@ -649,10 +625,10 @@ mod tests { post_id: inserted_post.id, locked: None, }; - let inserted_mod_lock_post = ModLockPost::create(conn, &mod_lock_post_form) + let inserted_mod_lock_post = ModLockPost::create(pool, &mod_lock_post_form) .await .unwrap(); - let read_mod_lock_post = ModLockPost::read(conn, inserted_mod_lock_post.id) + let read_mod_lock_post = ModLockPost::read(pool, inserted_mod_lock_post.id) .await .unwrap(); let expected_mod_lock_post = ModLockPost { @@ -671,10 +647,10 @@ mod tests { featured: false, is_featured_community: true, }; - let inserted_mod_feature_post = ModFeaturePost::create(conn, &mod_feature_post_form) + let inserted_mod_feature_post = ModFeaturePost::create(pool, &mod_feature_post_form) .await .unwrap(); - let read_mod_feature_post = ModFeaturePost::read(conn, inserted_mod_feature_post.id) + let read_mod_feature_post = ModFeaturePost::read(pool, inserted_mod_feature_post.id) .await .unwrap(); let expected_mod_feature_post = ModFeaturePost { @@ -694,14 +670,12 @@ mod tests { reason: None, removed: None, }; - let inserted_mod_remove_comment = - ModRemoveComment::create(conn, &mod_remove_comment_form) - .await - .unwrap(); - let read_mod_remove_comment = - ModRemoveComment::read(conn, inserted_mod_remove_comment.id) - .await - .unwrap(); + let inserted_mod_remove_comment = ModRemoveComment::create(pool, &mod_remove_comment_form) + .await + .unwrap(); + let read_mod_remove_comment = ModRemoveComment::read(pool, inserted_mod_remove_comment.id) + .await + .unwrap(); let expected_mod_remove_comment = ModRemoveComment { id: inserted_mod_remove_comment.id, comment_id: inserted_comment.id, @@ -721,11 +695,11 @@ mod tests { expires: None, }; let inserted_mod_remove_community = - ModRemoveCommunity::create(conn, &mod_remove_community_form) + ModRemoveCommunity::create(pool, &mod_remove_community_form) .await .unwrap(); let read_mod_remove_community = - ModRemoveCommunity::read(conn, inserted_mod_remove_community.id) + ModRemoveCommunity::read(pool, inserted_mod_remove_community.id) .await .unwrap(); let expected_mod_remove_community = ModRemoveCommunity { @@ -749,11 +723,11 @@ mod tests { expires: None, }; let inserted_mod_ban_from_community = - ModBanFromCommunity::create(conn, &mod_ban_from_community_form) + ModBanFromCommunity::create(pool, &mod_ban_from_community_form) .await .unwrap(); let read_mod_ban_from_community = - ModBanFromCommunity::read(conn, inserted_mod_ban_from_community.id) + ModBanFromCommunity::read(pool, inserted_mod_ban_from_community.id) .await .unwrap(); let expected_mod_ban_from_community = ModBanFromCommunity { @@ -776,8 +750,8 @@ mod tests { banned: None, expires: None, }; - let inserted_mod_ban = ModBan::create(conn, &mod_ban_form).await.unwrap(); - let read_mod_ban = ModBan::read(conn, inserted_mod_ban.id).await.unwrap(); + let inserted_mod_ban = ModBan::create(pool, &mod_ban_form).await.unwrap(); + let read_mod_ban = ModBan::read(pool, inserted_mod_ban.id).await.unwrap(); let expected_mod_ban = ModBan { id: inserted_mod_ban.id, mod_person_id: inserted_mod.id, @@ -796,10 +770,10 @@ mod tests { community_id: inserted_community.id, removed: None, }; - let inserted_mod_add_community = ModAddCommunity::create(conn, &mod_add_community_form) + let inserted_mod_add_community = ModAddCommunity::create(pool, &mod_add_community_form) .await .unwrap(); - let read_mod_add_community = ModAddCommunity::read(conn, inserted_mod_add_community.id) + let read_mod_add_community = ModAddCommunity::read(pool, inserted_mod_add_community.id) .await .unwrap(); let expected_mod_add_community = ModAddCommunity { @@ -818,8 +792,8 @@ mod tests { other_person_id: inserted_person.id, removed: None, }; - let inserted_mod_add = ModAdd::create(conn, &mod_add_form).await.unwrap(); - let read_mod_add = ModAdd::read(conn, inserted_mod_add.id).await.unwrap(); + let inserted_mod_add = ModAdd::create(pool, &mod_add_form).await.unwrap(); + let read_mod_add = ModAdd::read(pool, inserted_mod_add.id).await.unwrap(); let expected_mod_add = ModAdd { id: inserted_mod_add.id, mod_person_id: inserted_mod.id, @@ -828,20 +802,14 @@ mod tests { when_: inserted_mod_add.when_, }; - Comment::delete(conn, inserted_comment.id) - .await - .unwrap(); - Post::delete(conn, inserted_post.id).await.unwrap(); - Community::delete(conn, inserted_community.id) - .await - .unwrap(); - Person::delete(conn, inserted_person.id) - .await - .unwrap(); - Person::delete(conn, inserted_mod.id).await.unwrap(); - Instance::delete(conn, inserted_instance.id) + Comment::delete(pool, inserted_comment.id).await.unwrap(); + Post::delete(pool, inserted_post.id).await.unwrap(); + Community::delete(pool, inserted_community.id) .await .unwrap(); + Person::delete(pool, inserted_person.id).await.unwrap(); + Person::delete(pool, inserted_mod.id).await.unwrap(); + Instance::delete(pool, inserted_instance.id).await.unwrap(); assert_eq!(expected_mod_remove_post, read_mod_remove_post); assert_eq!(expected_mod_lock_post, read_mod_lock_post); diff --git a/crates/db_schema/src/impls/password_reset_request.rs b/crates/db_schema/src/impls/password_reset_request.rs index c5cc67e31..85ad4cf01 100644 --- a/crates/db_schema/src/impls/password_reset_request.rs +++ b/crates/db_schema/src/impls/password_reset_request.rs @@ -8,7 +8,7 @@ use crate::{ }, source::password_reset_request::{PasswordResetRequest, PasswordResetRequestForm}, traits::Crud, - utils::GetConn, + utils::{get_conn, DbPool}, }; use diesel::{ dsl::{insert_into, now, IntervalDsl}, @@ -16,7 +16,7 @@ use diesel::{ ExpressionMethods, QueryDsl, }; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::RunQueryDsl; use sha2::{Digest, Sha256}; #[async_trait] @@ -24,23 +24,26 @@ impl Crud for PasswordResetRequest { type InsertForm = PasswordResetRequestForm; type UpdateForm = PasswordResetRequestForm; type IdType = i32; - async fn read(mut conn: impl GetConn, password_reset_request_id: i32) -> Result { + async fn read(pool: &DbPool, password_reset_request_id: i32) -> Result { + let conn = &mut get_conn(pool).await?; password_reset_request .find(password_reset_request_id) .first::(conn) .await } - async fn create(mut conn: impl GetConn, form: &PasswordResetRequestForm) -> Result { + async fn create(pool: &DbPool, form: &PasswordResetRequestForm) -> Result { + let conn = &mut get_conn(pool).await?; insert_into(password_reset_request) .values(form) .get_result::(conn) .await } async fn update( - mut conn: impl GetConn, + pool: &DbPool, password_reset_request_id: i32, form: &PasswordResetRequestForm, ) -> Result { + let conn = &mut get_conn(pool).await?; diesel::update(password_reset_request.find(password_reset_request_id)) .set(form) .get_result::(conn) @@ -50,7 +53,7 @@ impl Crud for PasswordResetRequest { impl PasswordResetRequest { pub async fn create_token( - mut conn: impl GetConn, + pool: &DbPool, from_local_user_id: LocalUserId, token: &str, ) -> Result { @@ -63,12 +66,10 @@ impl PasswordResetRequest { token_encrypted: token_hash, }; - Self::create(conn, &form).await + Self::create(pool, &form).await } - pub async fn read_from_token( - mut conn: impl GetConn, - token: &str, - ) -> Result { + pub async fn read_from_token(pool: &DbPool, token: &str) -> Result { + let conn = &mut get_conn(pool).await?; let mut hasher = Sha256::new(); hasher.update(token); let token_hash: String = bytes_to_hex(hasher.finalize().to_vec()); @@ -80,9 +81,10 @@ impl PasswordResetRequest { } pub async fn get_recent_password_resets_count( - mut conn: impl GetConn, + pool: &DbPool, user_id: LocalUserId, ) -> Result { + let conn = &mut get_conn(pool).await?; password_reset_request .filter(local_user_id.eq(user_id)) .filter(published.gt(now - 1.days())) @@ -110,16 +112,16 @@ mod tests { person::{Person, PersonInsertForm}, }, traits::Crud, - utils::build_db_conn_for_tests, + utils::build_db_pool_for_tests, }; use serial_test::serial; #[tokio::test] #[serial] async fn test_crud() { - let mut conn = build_db_conn_for_tests().await; + let pool = &build_db_pool_for_tests().await; - let inserted_instance = Instance::read_or_create(conn, "my_domain.tld".to_string()) + let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()) .await .unwrap(); @@ -129,22 +131,20 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_person = Person::create(conn, &new_person).await.unwrap(); + let inserted_person = Person::create(pool, &new_person).await.unwrap(); let new_local_user = LocalUserInsertForm::builder() .person_id(inserted_person.id) .password_encrypted("pass".to_string()) .build(); - let inserted_local_user = LocalUser::create(conn, &new_local_user) - .await - .unwrap(); + let inserted_local_user = LocalUser::create(pool, &new_local_user).await.unwrap(); let token = "nope"; let token_encrypted_ = "ca3704aa0b06f5954c79ee837faa152d84d6b2d42838f0637a15eda8337dbdce"; let inserted_password_reset_request = - PasswordResetRequest::create_token(conn, inserted_local_user.id, token) + PasswordResetRequest::create_token(pool, inserted_local_user.id, token) .await .unwrap(); @@ -155,15 +155,11 @@ mod tests { published: inserted_password_reset_request.published, }; - let read_password_reset_request = PasswordResetRequest::read_from_token(conn, token) - .await - .unwrap(); - let num_deleted = Person::delete(conn, inserted_person.id) - .await - .unwrap(); - Instance::delete(conn, inserted_instance.id) + let read_password_reset_request = PasswordResetRequest::read_from_token(pool, token) .await .unwrap(); + let num_deleted = Person::delete(pool, inserted_person.id).await.unwrap(); + Instance::delete(pool, inserted_instance.id).await.unwrap(); assert_eq!(expected_password_reset_request, read_password_reset_request); assert_eq!( diff --git a/crates/db_schema/src/impls/person.rs b/crates/db_schema/src/impls/person.rs index 20ff7e33f..5c23f8071 100644 --- a/crates/db_schema/src/impls/person.rs +++ b/crates/db_schema/src/impls/person.rs @@ -9,39 +9,43 @@ use crate::{ PersonUpdateForm, }, traits::{ApubActor, Crud, Followable}, - utils::{functions::lower, naive_now, GetConn}, + utils::{functions::lower, get_conn, naive_now, DbPool}, }; use diesel::{dsl::insert_into, result::Error, ExpressionMethods, JoinOnDsl, QueryDsl}; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::RunQueryDsl; #[async_trait] impl Crud for Person { type InsertForm = PersonInsertForm; type UpdateForm = PersonUpdateForm; type IdType = PersonId; - async fn read(mut conn: impl GetConn, person_id: PersonId) -> Result { + async fn read(pool: &DbPool, person_id: PersonId) -> Result { + let conn = &mut get_conn(pool).await?; person::table .filter(person::deleted.eq(false)) .find(person_id) .first::(conn) .await } - async fn delete(mut conn: impl GetConn, person_id: PersonId) -> Result { + async fn delete(pool: &DbPool, person_id: PersonId) -> Result { + let conn = &mut get_conn(pool).await?; diesel::delete(person::table.find(person_id)) .execute(conn) .await } - async fn create(mut conn: impl GetConn, form: &PersonInsertForm) -> Result { + async fn create(pool: &DbPool, form: &PersonInsertForm) -> Result { + let conn = &mut get_conn(pool).await?; insert_into(person::table) .values(form) .get_result::(conn) .await } async fn update( - mut conn: impl GetConn, + pool: &DbPool, person_id: PersonId, form: &PersonUpdateForm, ) -> Result { + let conn = &mut get_conn(pool).await?; diesel::update(person::table.find(person_id)) .set(form) .get_result::(conn) @@ -53,7 +57,8 @@ impl Person { /// Update or insert the person. /// /// This is necessary for federation, because Activitypub doesnt distinguish between these actions. - pub async fn upsert(mut conn: impl GetConn, form: &PersonInsertForm) -> Result { + pub async fn upsert(pool: &DbPool, form: &PersonInsertForm) -> Result { + let conn = &mut get_conn(pool).await?; insert_into(person::table) .values(form) .on_conflict(person::actor_id) @@ -62,10 +67,9 @@ impl Person { .get_result::(conn) .await } - pub async fn delete_account( - mut conn: impl GetConn, - person_id: PersonId, - ) -> Result { + pub async fn delete_account(pool: &DbPool, person_id: PersonId) -> Result { + let conn = &mut get_conn(pool).await?; + // Set the local user info to none diesel::update(local_user::table.filter(local_user::person_id.eq(person_id))) .set(( @@ -100,10 +104,8 @@ pub fn is_banned(banned_: bool, expires: Option) -> bool #[async_trait] impl ApubActor for Person { - async fn read_from_apub_id( - mut conn: impl GetConn, - object_id: &DbUrl, - ) -> Result, Error> { + async fn read_from_apub_id(pool: &DbPool, object_id: &DbUrl) -> Result, Error> { + let conn = &mut get_conn(pool).await?; Ok( person::table .filter(person::deleted.eq(false)) @@ -116,10 +118,11 @@ impl ApubActor for Person { } async fn read_from_name( - mut conn: impl GetConn, + pool: &DbPool, from_name: &str, include_deleted: bool, ) -> Result { + let conn = &mut get_conn(pool).await?; let mut q = person::table .into_boxed() .filter(person::local.eq(true)) @@ -131,10 +134,12 @@ impl ApubActor for Person { } async fn read_from_name_and_domain( - mut conn: impl GetConn, + pool: &DbPool, person_name: &str, for_domain: &str, ) -> Result { + let conn = &mut get_conn(pool).await?; + person::table .inner_join(instance::table) .filter(lower(person::name).eq(person_name.to_lowercase())) @@ -148,8 +153,9 @@ impl ApubActor for Person { #[async_trait] impl Followable for PersonFollower { type Form = PersonFollowerForm; - async fn follow(mut conn: impl GetConn, form: &PersonFollowerForm) -> Result { + async fn follow(pool: &DbPool, form: &PersonFollowerForm) -> Result { use crate::schema::person_follower::dsl::{follower_id, person_follower, person_id}; + let conn = &mut get_conn(pool).await?; insert_into(person_follower) .values(form) .on_conflict((follower_id, person_id)) @@ -158,11 +164,12 @@ impl Followable for PersonFollower { .get_result::(conn) .await } - async fn follow_accepted(_: impl GetConn, _: CommunityId, _: PersonId) -> Result { + async fn follow_accepted(_: &DbPool, _: CommunityId, _: PersonId) -> Result { unimplemented!() } - async fn unfollow(mut conn: impl GetConn, form: &PersonFollowerForm) -> Result { + async fn unfollow(pool: &DbPool, form: &PersonFollowerForm) -> Result { use crate::schema::person_follower::dsl::{follower_id, person_follower, person_id}; + let conn = &mut get_conn(pool).await?; diesel::delete( person_follower .filter(follower_id.eq(&form.follower_id)) @@ -175,9 +182,10 @@ impl Followable for PersonFollower { impl PersonFollower { pub async fn list_followers( - mut conn: impl GetConn, + pool: &DbPool, for_person_id: PersonId, ) -> Result, Error> { + let conn = &mut get_conn(pool).await?; person_follower::table .inner_join(person::table.on(person_follower::follower_id.eq(person::id))) .filter(person_follower::person_id.eq(for_person_id)) @@ -195,16 +203,16 @@ mod tests { person::{Person, PersonFollower, PersonFollowerForm, PersonInsertForm, PersonUpdateForm}, }, traits::{Crud, Followable}, - utils::build_db_conn_for_tests, + utils::build_db_pool_for_tests, }; use serial_test::serial; #[tokio::test] #[serial] async fn test_crud() { - let mut conn = build_db_conn_for_tests().await; + let pool = &build_db_pool_for_tests().await; - let inserted_instance = Instance::read_or_create(conn, "my_domain.tld".to_string()) + let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()) .await .unwrap(); @@ -214,7 +222,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_person = Person::create(conn, &new_person).await.unwrap(); + let inserted_person = Person::create(pool, &new_person).await.unwrap(); let expected_person = Person { id: inserted_person.id, @@ -241,21 +249,17 @@ mod tests { instance_id: inserted_instance.id, }; - let read_person = Person::read(conn, inserted_person.id).await.unwrap(); + let read_person = Person::read(pool, inserted_person.id).await.unwrap(); let update_person_form = PersonUpdateForm::builder() .actor_id(Some(inserted_person.actor_id.clone())) .build(); - let updated_person = Person::update(conn, inserted_person.id, &update_person_form) + let updated_person = Person::update(pool, inserted_person.id, &update_person_form) .await .unwrap(); - let num_deleted = Person::delete(conn, inserted_person.id) - .await - .unwrap(); - Instance::delete(conn, inserted_instance.id) - .await - .unwrap(); + let num_deleted = Person::delete(pool, inserted_person.id).await.unwrap(); + Instance::delete(pool, inserted_instance.id).await.unwrap(); assert_eq!(expected_person, read_person); assert_eq!(expected_person, inserted_person); @@ -266,8 +270,8 @@ mod tests { #[tokio::test] #[serial] async fn follow() { - let mut conn = build_db_conn_for_tests().await; - let inserted_instance = Instance::read_or_create(conn, "my_domain.tld".to_string()) + let pool = &build_db_pool_for_tests().await; + let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()) .await .unwrap(); @@ -276,34 +280,30 @@ mod tests { .public_key("pubkey".to_string()) .instance_id(inserted_instance.id) .build(); - let person_1 = Person::create(conn, &person_form_1).await.unwrap(); + let person_1 = Person::create(pool, &person_form_1).await.unwrap(); let person_form_2 = PersonInsertForm::builder() .name("michele".into()) .public_key("pubkey".to_string()) .instance_id(inserted_instance.id) .build(); - let person_2 = Person::create(conn, &person_form_2).await.unwrap(); + let person_2 = Person::create(pool, &person_form_2).await.unwrap(); let follow_form = PersonFollowerForm { person_id: person_1.id, follower_id: person_2.id, pending: false, }; - let person_follower = PersonFollower::follow(conn, &follow_form) - .await - .unwrap(); + let person_follower = PersonFollower::follow(pool, &follow_form).await.unwrap(); assert_eq!(person_1.id, person_follower.person_id); assert_eq!(person_2.id, person_follower.follower_id); assert!(!person_follower.pending); - let followers = PersonFollower::list_followers(conn, person_1.id) + let followers = PersonFollower::list_followers(pool, person_1.id) .await .unwrap(); assert_eq!(vec![person_2], followers); - let unfollow = PersonFollower::unfollow(conn, &follow_form) - .await - .unwrap(); + let unfollow = PersonFollower::unfollow(pool, &follow_form).await.unwrap(); assert_eq!(1, unfollow); } } diff --git a/crates/db_schema/src/impls/person_block.rs b/crates/db_schema/src/impls/person_block.rs index c243d5549..9cd275563 100644 --- a/crates/db_schema/src/impls/person_block.rs +++ b/crates/db_schema/src/impls/person_block.rs @@ -3,17 +3,18 @@ use crate::{ schema::person_block::dsl::{person_block, person_id, target_id}, source::person_block::{PersonBlock, PersonBlockForm}, traits::Blockable, - utils::GetConn, + utils::{get_conn, DbPool}, }; use diesel::{dsl::insert_into, result::Error, ExpressionMethods, QueryDsl}; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::RunQueryDsl; impl PersonBlock { pub async fn read( - mut conn: impl GetConn, + pool: &DbPool, for_person_id: PersonId, for_recipient_id: PersonId, ) -> Result { + let conn = &mut get_conn(pool).await?; person_block .filter(person_id.eq(for_person_id)) .filter(target_id.eq(for_recipient_id)) @@ -25,10 +26,8 @@ impl PersonBlock { #[async_trait] impl Blockable for PersonBlock { type Form = PersonBlockForm; - async fn block( - mut conn: impl GetConn, - person_block_form: &PersonBlockForm, - ) -> Result { + async fn block(pool: &DbPool, person_block_form: &PersonBlockForm) -> Result { + let conn = &mut get_conn(pool).await?; insert_into(person_block) .values(person_block_form) .on_conflict((person_id, target_id)) @@ -37,7 +36,8 @@ impl Blockable for PersonBlock { .get_result::(conn) .await } - async fn unblock(mut conn: impl GetConn, person_block_form: &Self::Form) -> Result { + async fn unblock(pool: &DbPool, person_block_form: &Self::Form) -> Result { + let conn = &mut get_conn(pool).await?; diesel::delete( person_block .filter(person_id.eq(person_block_form.person_id)) diff --git a/crates/db_schema/src/impls/person_mention.rs b/crates/db_schema/src/impls/person_mention.rs index e6beb7795..559340e78 100644 --- a/crates/db_schema/src/impls/person_mention.rs +++ b/crates/db_schema/src/impls/person_mention.rs @@ -3,27 +3,26 @@ use crate::{ schema::person_mention::dsl::{comment_id, person_mention, read, recipient_id}, source::person_mention::{PersonMention, PersonMentionInsertForm, PersonMentionUpdateForm}, traits::Crud, - utils::GetConn, + utils::{get_conn, DbPool}, }; use diesel::{dsl::insert_into, result::Error, ExpressionMethods, QueryDsl}; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::RunQueryDsl; #[async_trait] impl Crud for PersonMention { type InsertForm = PersonMentionInsertForm; type UpdateForm = PersonMentionUpdateForm; type IdType = PersonMentionId; - async fn read(mut conn: impl GetConn, person_mention_id: PersonMentionId) -> Result { + async fn read(pool: &DbPool, person_mention_id: PersonMentionId) -> Result { + let conn = &mut get_conn(pool).await?; person_mention .find(person_mention_id) .first::(conn) .await } - async fn create( - mut conn: impl GetConn, - person_mention_form: &Self::InsertForm, - ) -> Result { + async fn create(pool: &DbPool, person_mention_form: &Self::InsertForm) -> Result { + let conn = &mut get_conn(pool).await?; // since the return here isnt utilized, we dont need to do an update // but get_result doesnt return the existing row here insert_into(person_mention) @@ -36,10 +35,11 @@ impl Crud for PersonMention { } async fn update( - mut conn: impl GetConn, + pool: &DbPool, person_mention_id: PersonMentionId, person_mention_form: &Self::UpdateForm, ) -> Result { + let conn = &mut get_conn(pool).await?; diesel::update(person_mention.find(person_mention_id)) .set(person_mention_form) .get_result::(conn) @@ -49,9 +49,10 @@ impl Crud for PersonMention { impl PersonMention { pub async fn mark_all_as_read( - mut conn: impl GetConn, + pool: &DbPool, for_recipient_id: PersonId, ) -> Result, Error> { + let conn = &mut get_conn(pool).await?; diesel::update( person_mention .filter(recipient_id.eq(for_recipient_id)) @@ -63,10 +64,11 @@ impl PersonMention { } pub async fn read_by_comment_and_person( - mut conn: impl GetConn, + pool: &DbPool, for_comment_id: CommentId, for_recipient_id: PersonId, ) -> Result { + let conn = &mut get_conn(pool).await?; person_mention .filter(comment_id.eq(for_comment_id)) .filter(recipient_id.eq(for_recipient_id)) @@ -87,16 +89,16 @@ mod tests { post::{Post, PostInsertForm}, }, traits::Crud, - utils::build_db_conn_for_tests, + utils::build_db_pool_for_tests, }; use serial_test::serial; #[tokio::test] #[serial] async fn test_crud() { - let mut conn = build_db_conn_for_tests().await; + let pool = &build_db_pool_for_tests().await; - let inserted_instance = Instance::read_or_create(conn, "my_domain.tld".to_string()) + let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()) .await .unwrap(); @@ -106,7 +108,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_person = Person::create(conn, &new_person).await.unwrap(); + let inserted_person = Person::create(pool, &new_person).await.unwrap(); let recipient_form = PersonInsertForm::builder() .name("terrylakes recipient".into()) @@ -114,7 +116,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_recipient = Person::create(conn, &recipient_form).await.unwrap(); + let inserted_recipient = Person::create(pool, &recipient_form).await.unwrap(); let new_community = CommunityInsertForm::builder() .name("test community lake".to_string()) @@ -123,7 +125,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_community = Community::create(conn, &new_community).await.unwrap(); + let inserted_community = Community::create(pool, &new_community).await.unwrap(); let new_post = PostInsertForm::builder() .name("A test post".into()) @@ -131,7 +133,7 @@ mod tests { .community_id(inserted_community.id) .build(); - let inserted_post = Post::create(conn, &new_post).await.unwrap(); + let inserted_post = Post::create(pool, &new_post).await.unwrap(); let comment_form = CommentInsertForm::builder() .content("A test comment".into()) @@ -139,9 +141,7 @@ mod tests { .post_id(inserted_post.id) .build(); - let inserted_comment = Comment::create(conn, &comment_form, None) - .await - .unwrap(); + let inserted_comment = Comment::create(pool, &comment_form, None).await.unwrap(); let person_mention_form = PersonMentionInsertForm { recipient_id: inserted_recipient.id, @@ -149,7 +149,7 @@ mod tests { read: None, }; - let inserted_mention = PersonMention::create(conn, &person_mention_form) + let inserted_mention = PersonMention::create(pool, &person_mention_form) .await .unwrap(); @@ -161,31 +161,23 @@ mod tests { published: inserted_mention.published, }; - let read_mention = PersonMention::read(conn, inserted_mention.id) + let read_mention = PersonMention::read(pool, inserted_mention.id) .await .unwrap(); let person_mention_update_form = PersonMentionUpdateForm { read: Some(false) }; let updated_mention = - PersonMention::update(conn, inserted_mention.id, &person_mention_update_form) + PersonMention::update(pool, inserted_mention.id, &person_mention_update_form) .await .unwrap(); - Comment::delete(conn, inserted_comment.id) - .await - .unwrap(); - Post::delete(conn, inserted_post.id).await.unwrap(); - Community::delete(conn, inserted_community.id) - .await - .unwrap(); - Person::delete(conn, inserted_person.id) - .await - .unwrap(); - Person::delete(conn, inserted_recipient.id) - .await - .unwrap(); - Instance::delete(conn, inserted_instance.id) + Comment::delete(pool, inserted_comment.id).await.unwrap(); + Post::delete(pool, inserted_post.id).await.unwrap(); + Community::delete(pool, inserted_community.id) .await .unwrap(); + Person::delete(pool, inserted_person.id).await.unwrap(); + Person::delete(pool, inserted_recipient.id).await.unwrap(); + Instance::delete(pool, inserted_instance.id).await.unwrap(); assert_eq!(expected_mention, read_mention); assert_eq!(expected_mention, inserted_mention); diff --git a/crates/db_schema/src/impls/post.rs b/crates/db_schema/src/impls/post.rs index d24765be9..6a4d53d3a 100644 --- a/crates/db_schema/src/impls/post.rs +++ b/crates/db_schema/src/impls/post.rs @@ -27,26 +27,29 @@ use crate::{ PostUpdateForm, }, traits::{Crud, Likeable, Readable, Saveable}, - utils::{naive_now, GetConn, DELETED_REPLACEMENT_TEXT, FETCH_LIMIT_MAX}, + utils::{get_conn, naive_now, DbPool, DELETED_REPLACEMENT_TEXT, FETCH_LIMIT_MAX}, }; use ::url::Url; use diesel::{dsl::insert_into, result::Error, ExpressionMethods, QueryDsl, TextExpressionMethods}; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::RunQueryDsl; #[async_trait] impl Crud for Post { type InsertForm = PostInsertForm; type UpdateForm = PostUpdateForm; type IdType = PostId; - async fn read(mut conn: impl GetConn, post_id: PostId) -> Result { + async fn read(pool: &DbPool, post_id: PostId) -> Result { + let conn = &mut get_conn(pool).await?; post.find(post_id).first::(conn).await } - async fn delete(mut conn: impl GetConn, post_id: PostId) -> Result { + async fn delete(pool: &DbPool, post_id: PostId) -> Result { + let conn = &mut get_conn(pool).await?; diesel::delete(post.find(post_id)).execute(conn).await } - async fn create(mut conn: impl GetConn, form: &Self::InsertForm) -> Result { + async fn create(pool: &DbPool, form: &Self::InsertForm) -> Result { + let conn = &mut get_conn(pool).await?; insert_into(post) .values(form) .on_conflict(ap_id) @@ -57,10 +60,11 @@ impl Crud for Post { } async fn update( - mut conn: impl GetConn, + pool: &DbPool, post_id: PostId, new_post: &Self::UpdateForm, ) -> Result { + let conn = &mut get_conn(pool).await?; diesel::update(post.find(post_id)) .set(new_post) .get_result::(conn) @@ -70,9 +74,10 @@ impl Crud for Post { impl Post { pub async fn list_for_community( - mut conn: impl GetConn, + pool: &DbPool, the_community_id: CommunityId, ) -> Result, Error> { + let conn = &mut get_conn(pool).await?; post .filter(community_id.eq(the_community_id)) .filter(deleted.eq(false)) @@ -85,9 +90,10 @@ impl Post { } pub async fn list_featured_for_community( - mut conn: impl GetConn, + pool: &DbPool, the_community_id: CommunityId, ) -> Result, Error> { + let conn = &mut get_conn(pool).await?; post .filter(community_id.eq(the_community_id)) .filter(deleted.eq(false)) @@ -100,9 +106,11 @@ impl Post { } pub async fn permadelete_for_creator( - mut conn: impl GetConn, + pool: &DbPool, for_creator_id: PersonId, ) -> Result, Error> { + let conn = &mut get_conn(pool).await?; + diesel::update(post.filter(creator_id.eq(for_creator_id))) .set(( name.eq(DELETED_REPLACEMENT_TEXT), @@ -116,11 +124,13 @@ impl Post { } pub async fn update_removed_for_creator( - mut conn: impl GetConn, + pool: &DbPool, for_creator_id: PersonId, for_community_id: Option, new_removed: bool, ) -> Result, Error> { + let conn = &mut get_conn(pool).await?; + let mut update = diesel::update(post).into_boxed(); update = update.filter(creator_id.eq(for_creator_id)); @@ -138,10 +148,8 @@ impl Post { person_id == post_creator_id } - pub async fn read_from_apub_id( - mut conn: impl GetConn, - object_id: Url, - ) -> Result, Error> { + pub async fn read_from_apub_id(pool: &DbPool, object_id: Url) -> Result, Error> { + let conn = &mut get_conn(pool).await?; let object_id: DbUrl = object_id.into(); Ok( post @@ -154,9 +162,10 @@ impl Post { } pub async fn fetch_pictrs_posts_for_creator( - mut conn: impl GetConn, + pool: &DbPool, for_creator_id: PersonId, ) -> Result, Error> { + let conn = &mut get_conn(pool).await?; let pictrs_search = "%pictrs/image%"; post @@ -168,9 +177,10 @@ impl Post { /// Sets the url and thumbnails fields to None pub async fn remove_pictrs_post_images_and_thumbnails_for_creator( - mut conn: impl GetConn, + pool: &DbPool, for_creator_id: PersonId, ) -> Result, Error> { + let conn = &mut get_conn(pool).await?; let pictrs_search = "%pictrs/image%"; diesel::update( @@ -187,9 +197,10 @@ impl Post { } pub async fn fetch_pictrs_posts_for_community( - mut conn: impl GetConn, + pool: &DbPool, for_community_id: CommunityId, ) -> Result, Error> { + let conn = &mut get_conn(pool).await?; let pictrs_search = "%pictrs/image%"; post .filter(community_id.eq(for_community_id)) @@ -200,9 +211,10 @@ impl Post { /// Sets the url and thumbnails fields to None pub async fn remove_pictrs_post_images_and_thumbnails_for_community( - mut conn: impl GetConn, + pool: &DbPool, for_community_id: CommunityId, ) -> Result, Error> { + let conn = &mut get_conn(pool).await?; let pictrs_search = "%pictrs/image%"; diesel::update( @@ -223,8 +235,9 @@ impl Post { impl Likeable for PostLike { type Form = PostLikeForm; type IdType = PostId; - async fn like(mut conn: impl GetConn, post_like_form: &PostLikeForm) -> Result { + async fn like(pool: &DbPool, post_like_form: &PostLikeForm) -> Result { use crate::schema::post_like::dsl::{person_id, post_id, post_like}; + let conn = &mut get_conn(pool).await?; insert_into(post_like) .values(post_like_form) .on_conflict((post_id, person_id)) @@ -233,12 +246,9 @@ impl Likeable for PostLike { .get_result::(conn) .await } - async fn remove( - mut conn: impl GetConn, - person_id: PersonId, - post_id: PostId, - ) -> Result { + async fn remove(pool: &DbPool, person_id: PersonId, post_id: PostId) -> Result { use crate::schema::post_like::dsl; + let conn = &mut get_conn(pool).await?; diesel::delete( dsl::post_like .filter(dsl::post_id.eq(post_id)) @@ -252,8 +262,9 @@ impl Likeable for PostLike { #[async_trait] impl Saveable for PostSaved { type Form = PostSavedForm; - async fn save(mut conn: impl GetConn, post_saved_form: &PostSavedForm) -> Result { + async fn save(pool: &DbPool, post_saved_form: &PostSavedForm) -> Result { use crate::schema::post_saved::dsl::{person_id, post_id, post_saved}; + let conn = &mut get_conn(pool).await?; insert_into(post_saved) .values(post_saved_form) .on_conflict((post_id, person_id)) @@ -262,8 +273,9 @@ impl Saveable for PostSaved { .get_result::(conn) .await } - async fn unsave(mut conn: impl GetConn, post_saved_form: &PostSavedForm) -> Result { + async fn unsave(pool: &DbPool, post_saved_form: &PostSavedForm) -> Result { use crate::schema::post_saved::dsl::{person_id, post_id, post_saved}; + let conn = &mut get_conn(pool).await?; diesel::delete( post_saved .filter(post_id.eq(post_saved_form.post_id)) @@ -277,11 +289,9 @@ impl Saveable for PostSaved { #[async_trait] impl Readable for PostRead { type Form = PostReadForm; - async fn mark_as_read( - mut conn: impl GetConn, - post_read_form: &PostReadForm, - ) -> Result { + async fn mark_as_read(pool: &DbPool, post_read_form: &PostReadForm) -> Result { use crate::schema::post_read::dsl::{person_id, post_id, post_read}; + let conn = &mut get_conn(pool).await?; insert_into(post_read) .values(post_read_form) .on_conflict((post_id, person_id)) @@ -291,11 +301,9 @@ impl Readable for PostRead { .await } - async fn mark_as_unread( - mut conn: impl GetConn, - post_read_form: &PostReadForm, - ) -> Result { + async fn mark_as_unread(pool: &DbPool, post_read_form: &PostReadForm) -> Result { use crate::schema::post_read::dsl::{person_id, post_id, post_read}; + let conn = &mut get_conn(pool).await?; diesel::delete( post_read .filter(post_id.eq(post_read_form.post_id)) @@ -326,16 +334,16 @@ mod tests { }, }, traits::{Crud, Likeable, Readable, Saveable}, - utils::build_db_conn_for_tests, + utils::build_db_pool_for_tests, }; use serial_test::serial; #[tokio::test] #[serial] async fn test_crud() { - let mut conn = build_db_conn_for_tests().await; + let pool = &build_db_pool_for_tests().await; - let inserted_instance = Instance::read_or_create(conn, "my_domain.tld".to_string()) + let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()) .await .unwrap(); @@ -345,7 +353,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_person = Person::create(conn, &new_person).await.unwrap(); + let inserted_person = Person::create(pool, &new_person).await.unwrap(); let new_community = CommunityInsertForm::builder() .name("test community_3".to_string()) @@ -354,7 +362,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_community = Community::create(conn, &new_community).await.unwrap(); + let inserted_community = Community::create(pool, &new_community).await.unwrap(); let new_post = PostInsertForm::builder() .name("A test post".into()) @@ -362,7 +370,7 @@ mod tests { .community_id(inserted_community.id) .build(); - let inserted_post = Post::create(conn, &new_post).await.unwrap(); + let inserted_post = Post::create(pool, &new_post).await.unwrap(); let expected_post = Post { id: inserted_post.id, @@ -395,7 +403,7 @@ mod tests { score: 1, }; - let inserted_post_like = PostLike::like(conn, &post_like_form).await.unwrap(); + let inserted_post_like = PostLike::like(pool, &post_like_form).await.unwrap(); let expected_post_like = PostLike { id: inserted_post_like.id, @@ -411,7 +419,7 @@ mod tests { person_id: inserted_person.id, }; - let inserted_post_saved = PostSaved::save(conn, &post_saved_form).await.unwrap(); + let inserted_post_saved = PostSaved::save(pool, &post_saved_form).await.unwrap(); let expected_post_saved = PostSaved { id: inserted_post_saved.id, @@ -426,9 +434,7 @@ mod tests { person_id: inserted_person.id, }; - let inserted_post_read = PostRead::mark_as_read(conn, &post_read_form) - .await - .unwrap(); + let inserted_post_read = PostRead::mark_as_read(pool, &post_read_form).await.unwrap(); let expected_post_read = PostRead { id: inserted_post_read.id, @@ -437,34 +443,28 @@ mod tests { published: inserted_post_read.published, }; - let read_post = Post::read(conn, inserted_post.id).await.unwrap(); + let read_post = Post::read(pool, inserted_post.id).await.unwrap(); let new_post_update = PostUpdateForm::builder() .name(Some("A test post".into())) .build(); - let updated_post = Post::update(conn, inserted_post.id, &new_post_update) + let updated_post = Post::update(pool, inserted_post.id, &new_post_update) .await .unwrap(); - let like_removed = PostLike::remove(conn, inserted_person.id, inserted_post.id) + let like_removed = PostLike::remove(pool, inserted_person.id, inserted_post.id) .await .unwrap(); - let saved_removed = PostSaved::unsave(conn, &post_saved_form) + let saved_removed = PostSaved::unsave(pool, &post_saved_form).await.unwrap(); + let read_removed = PostRead::mark_as_unread(pool, &post_read_form) .await .unwrap(); - let read_removed = PostRead::mark_as_unread(conn, &post_read_form) - .await - .unwrap(); - let num_deleted = Post::delete(conn, inserted_post.id).await.unwrap(); - Community::delete(conn, inserted_community.id) - .await - .unwrap(); - Person::delete(conn, inserted_person.id) - .await - .unwrap(); - Instance::delete(conn, inserted_instance.id) + let num_deleted = Post::delete(pool, inserted_post.id).await.unwrap(); + Community::delete(pool, inserted_community.id) .await .unwrap(); + Person::delete(pool, inserted_person.id).await.unwrap(); + Instance::delete(pool, inserted_instance.id).await.unwrap(); assert_eq!(expected_post, read_post); assert_eq!(expected_post, inserted_post); diff --git a/crates/db_schema/src/impls/post_report.rs b/crates/db_schema/src/impls/post_report.rs index 0fa1e54cd..ece7d0901 100644 --- a/crates/db_schema/src/impls/post_report.rs +++ b/crates/db_schema/src/impls/post_report.rs @@ -3,7 +3,7 @@ use crate::{ schema::post_report::dsl::{post_report, resolved, resolver_id, updated}, source::post_report::{PostReport, PostReportForm}, traits::Reportable, - utils::{naive_now, GetConn}, + utils::{get_conn, naive_now, DbPool}, }; use diesel::{ dsl::{insert_into, update}, @@ -11,17 +11,15 @@ use diesel::{ ExpressionMethods, QueryDsl, }; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::RunQueryDsl; #[async_trait] impl Reportable for PostReport { type Form = PostReportForm; type IdType = PostReportId; - async fn report( - mut conn: impl GetConn, - post_report_form: &PostReportForm, - ) -> Result { + async fn report(pool: &DbPool, post_report_form: &PostReportForm) -> Result { + let conn = &mut get_conn(pool).await?; insert_into(post_report) .values(post_report_form) .get_result::(conn) @@ -29,10 +27,11 @@ impl Reportable for PostReport { } async fn resolve( - mut conn: impl GetConn, + pool: &DbPool, report_id: Self::IdType, by_resolver_id: PersonId, ) -> Result { + let conn = &mut get_conn(pool).await?; update(post_report.find(report_id)) .set(( resolved.eq(true), @@ -44,10 +43,11 @@ impl Reportable for PostReport { } async fn unresolve( - mut conn: impl GetConn, + pool: &DbPool, report_id: Self::IdType, by_resolver_id: PersonId, ) -> Result { + let conn = &mut get_conn(pool).await?; update(post_report.find(report_id)) .set(( resolved.eq(false), diff --git a/crates/db_schema/src/impls/private_message.rs b/crates/db_schema/src/impls/private_message.rs index ab1f18f71..cf6782270 100644 --- a/crates/db_schema/src/impls/private_message.rs +++ b/crates/db_schema/src/impls/private_message.rs @@ -3,10 +3,10 @@ use crate::{ schema::private_message::dsl::{ap_id, private_message, read, recipient_id}, source::private_message::{PrivateMessage, PrivateMessageInsertForm, PrivateMessageUpdateForm}, traits::Crud, - utils::GetConn, + utils::{get_conn, DbPool}, }; use diesel::{dsl::insert_into, result::Error, ExpressionMethods, QueryDsl}; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::RunQueryDsl; use lemmy_utils::error::LemmyError; use url::Url; @@ -15,17 +15,16 @@ impl Crud for PrivateMessage { type InsertForm = PrivateMessageInsertForm; type UpdateForm = PrivateMessageUpdateForm; type IdType = PrivateMessageId; - async fn read( - mut conn: impl GetConn, - private_message_id: PrivateMessageId, - ) -> Result { + async fn read(pool: &DbPool, private_message_id: PrivateMessageId) -> Result { + let conn = &mut get_conn(pool).await?; private_message .find(private_message_id) .first::(conn) .await } - async fn create(mut conn: impl GetConn, form: &Self::InsertForm) -> Result { + async fn create(pool: &DbPool, form: &Self::InsertForm) -> Result { + let conn = &mut get_conn(pool).await?; insert_into(private_message) .values(form) .on_conflict(ap_id) @@ -36,16 +35,18 @@ impl Crud for PrivateMessage { } async fn update( - mut conn: impl GetConn, + pool: &DbPool, private_message_id: PrivateMessageId, form: &Self::UpdateForm, ) -> Result { + let conn = &mut get_conn(pool).await?; diesel::update(private_message.find(private_message_id)) .set(form) .get_result::(conn) .await } - async fn delete(mut conn: impl GetConn, pm_id: Self::IdType) -> Result { + async fn delete(pool: &DbPool, pm_id: Self::IdType) -> Result { + let conn = &mut get_conn(pool).await?; diesel::delete(private_message.find(pm_id)) .execute(conn) .await @@ -54,9 +55,10 @@ impl Crud for PrivateMessage { impl PrivateMessage { pub async fn mark_all_as_read( - mut conn: impl GetConn, + pool: &DbPool, for_recipient_id: PersonId, ) -> Result, Error> { + let conn = &mut get_conn(pool).await?; diesel::update( private_message .filter(recipient_id.eq(for_recipient_id)) @@ -68,9 +70,10 @@ impl PrivateMessage { } pub async fn read_from_apub_id( - mut conn: impl GetConn, + pool: &DbPool, object_id: Url, ) -> Result, LemmyError> { + let conn = &mut get_conn(pool).await?; let object_id: DbUrl = object_id.into(); Ok( private_message @@ -92,16 +95,16 @@ mod tests { private_message::{PrivateMessage, PrivateMessageInsertForm, PrivateMessageUpdateForm}, }, traits::Crud, - utils::build_db_conn_for_tests, + utils::build_db_pool_for_tests, }; use serial_test::serial; #[tokio::test] #[serial] async fn test_crud() { - let mut conn = build_db_conn_for_tests().await; + let pool = &build_db_pool_for_tests().await; - let inserted_instance = Instance::read_or_create(conn, "my_domain.tld".to_string()) + let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()) .await .unwrap(); @@ -111,7 +114,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_creator = Person::create(conn, &creator_form).await.unwrap(); + let inserted_creator = Person::create(pool, &creator_form).await.unwrap(); let recipient_form = PersonInsertForm::builder() .name("recipient_pm".into()) @@ -119,7 +122,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_recipient = Person::create(conn, &recipient_form).await.unwrap(); + let inserted_recipient = Person::create(pool, &recipient_form).await.unwrap(); let private_message_form = PrivateMessageInsertForm::builder() .content("A test private message".into()) @@ -127,7 +130,7 @@ mod tests { .recipient_id(inserted_recipient.id) .build(); - let inserted_private_message = PrivateMessage::create(conn, &private_message_form) + let inserted_private_message = PrivateMessage::create(pool, &private_message_form) .await .unwrap(); @@ -144,7 +147,7 @@ mod tests { local: true, }; - let read_private_message = PrivateMessage::read(conn, inserted_private_message.id) + let read_private_message = PrivateMessage::read(pool, inserted_private_message.id) .await .unwrap(); @@ -152,7 +155,7 @@ mod tests { .content(Some("A test private message".into())) .build(); let updated_private_message = PrivateMessage::update( - conn, + pool, inserted_private_message.id, &private_message_update_form, ) @@ -160,7 +163,7 @@ mod tests { .unwrap(); let deleted_private_message = PrivateMessage::update( - conn, + pool, inserted_private_message.id, &PrivateMessageUpdateForm::builder() .deleted(Some(true)) @@ -169,21 +172,15 @@ mod tests { .await .unwrap(); let marked_read_private_message = PrivateMessage::update( - conn, + pool, inserted_private_message.id, &PrivateMessageUpdateForm::builder().read(Some(true)).build(), ) .await .unwrap(); - Person::delete(conn, inserted_creator.id) - .await - .unwrap(); - Person::delete(conn, inserted_recipient.id) - .await - .unwrap(); - Instance::delete(conn, inserted_instance.id) - .await - .unwrap(); + Person::delete(pool, inserted_creator.id).await.unwrap(); + Person::delete(pool, inserted_recipient.id).await.unwrap(); + Instance::delete(pool, inserted_instance.id).await.unwrap(); assert_eq!(expected_private_message, read_private_message); assert_eq!(expected_private_message, updated_private_message); diff --git a/crates/db_schema/src/impls/private_message_report.rs b/crates/db_schema/src/impls/private_message_report.rs index c69b2c47f..5f2498c28 100644 --- a/crates/db_schema/src/impls/private_message_report.rs +++ b/crates/db_schema/src/impls/private_message_report.rs @@ -3,7 +3,7 @@ use crate::{ schema::private_message_report::dsl::{private_message_report, resolved, resolver_id, updated}, source::private_message_report::{PrivateMessageReport, PrivateMessageReportForm}, traits::Reportable, - utils::{naive_now, GetConn}, + utils::{get_conn, naive_now, DbPool}, }; use diesel::{ dsl::{insert_into, update}, @@ -11,17 +11,15 @@ use diesel::{ ExpressionMethods, QueryDsl, }; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::RunQueryDsl; #[async_trait] impl Reportable for PrivateMessageReport { type Form = PrivateMessageReportForm; type IdType = PrivateMessageReportId; - async fn report( - mut conn: impl GetConn, - pm_report_form: &PrivateMessageReportForm, - ) -> Result { + async fn report(pool: &DbPool, pm_report_form: &PrivateMessageReportForm) -> Result { + let conn = &mut get_conn(pool).await?; insert_into(private_message_report) .values(pm_report_form) .get_result::(conn) @@ -29,10 +27,11 @@ impl Reportable for PrivateMessageReport { } async fn resolve( - mut conn: impl GetConn, + pool: &DbPool, report_id: Self::IdType, by_resolver_id: PersonId, ) -> Result { + let conn = &mut get_conn(pool).await?; update(private_message_report.find(report_id)) .set(( resolved.eq(true), @@ -44,10 +43,11 @@ impl Reportable for PrivateMessageReport { } async fn unresolve( - mut conn: impl GetConn, + pool: &DbPool, report_id: Self::IdType, by_resolver_id: PersonId, ) -> Result { + let conn = &mut get_conn(pool).await?; update(private_message_report.find(report_id)) .set(( resolved.eq(false), diff --git a/crates/db_schema/src/impls/registration_application.rs b/crates/db_schema/src/impls/registration_application.rs index 666d58b6e..208b01d01 100644 --- a/crates/db_schema/src/impls/registration_application.rs +++ b/crates/db_schema/src/impls/registration_application.rs @@ -7,10 +7,10 @@ use crate::{ RegistrationApplicationUpdateForm, }, traits::Crud, - utils::GetConn, + utils::{get_conn, DbPool}, }; use diesel::{insert_into, result::Error, ExpressionMethods, QueryDsl}; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::RunQueryDsl; #[async_trait] impl Crud for RegistrationApplication { @@ -18,32 +18,33 @@ impl Crud for RegistrationApplication { type UpdateForm = RegistrationApplicationUpdateForm; type IdType = i32; - async fn create(mut conn: impl GetConn, form: &Self::InsertForm) -> Result { + async fn create(pool: &DbPool, form: &Self::InsertForm) -> Result { + let conn = &mut get_conn(pool).await?; insert_into(registration_application) .values(form) .get_result::(conn) .await } - async fn read(mut conn: impl GetConn, id_: Self::IdType) -> Result { - registration_application - .find(id_) - .first::(conn) - .await + async fn read(pool: &DbPool, id_: Self::IdType) -> Result { + let conn = &mut get_conn(pool).await?; + registration_application.find(id_).first::(conn).await } async fn update( - mut conn: impl GetConn, + pool: &DbPool, id_: Self::IdType, form: &Self::UpdateForm, ) -> Result { + let conn = &mut get_conn(pool).await?; diesel::update(registration_application.find(id_)) .set(form) .get_result::(conn) .await } - async fn delete(mut conn: impl GetConn, id_: Self::IdType) -> Result { + async fn delete(pool: &DbPool, id_: Self::IdType) -> Result { + let conn = &mut get_conn(pool).await?; diesel::delete(registration_application.find(id_)) .execute(conn) .await @@ -52,9 +53,10 @@ impl Crud for RegistrationApplication { impl RegistrationApplication { pub async fn find_by_local_user_id( - mut conn: impl GetConn, + pool: &DbPool, local_user_id_: LocalUserId, ) -> Result { + let conn = &mut get_conn(pool).await?; registration_application .filter(local_user_id.eq(local_user_id_)) .first::(conn) diff --git a/crates/db_schema/src/impls/secret.rs b/crates/db_schema/src/impls/secret.rs index 015fd6aa0..4e0d9c1bd 100644 --- a/crates/db_schema/src/impls/secret.rs +++ b/crates/db_schema/src/impls/secret.rs @@ -1,15 +1,20 @@ -use crate::{schema::secret::dsl::secret, source::secret::Secret, utils::GetConn}; +use crate::{ + schema::secret::dsl::secret, + source::secret::Secret, + utils::{get_conn, DbPool}, +}; use diesel::result::Error; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::RunQueryDsl; impl Secret { /// Initialize the Secrets from the DB. /// Warning: You should only call this once. - pub async fn init(mut conn: impl GetConn) -> Result { - Self::read_secrets(conn).await + pub async fn init(pool: &DbPool) -> Result { + Self::read_secrets(pool).await } - async fn read_secrets(mut conn: impl GetConn) -> Result { + async fn read_secrets(pool: &DbPool) -> Result { + let conn = &mut get_conn(pool).await?; secret.first::(conn).await } } diff --git a/crates/db_schema/src/impls/site.rs b/crates/db_schema/src/impls/site.rs index e6eb3de4d..3363edc93 100644 --- a/crates/db_schema/src/impls/site.rs +++ b/crates/db_schema/src/impls/site.rs @@ -6,10 +6,10 @@ use crate::{ site::{Site, SiteInsertForm, SiteUpdateForm}, }, traits::Crud, - utils::GetConn, + utils::{get_conn, DbPool}, }; use diesel::{dsl::insert_into, result::Error, ExpressionMethods, QueryDsl}; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::RunQueryDsl; use url::Url; #[async_trait] @@ -19,13 +19,14 @@ impl Crud for Site { type IdType = SiteId; /// Use SiteView::read_local, or Site::read_from_apub_id instead - async fn read(_conn: impl GetConn, _site_id: SiteId) -> Result { + async fn read(_pool: &DbPool, _site_id: SiteId) -> Result { unimplemented!() } - async fn create(mut conn: impl GetConn, form: &Self::InsertForm) -> Result { + async fn create(pool: &DbPool, form: &Self::InsertForm) -> Result { + let conn = &mut get_conn(pool).await?; let is_new_site = match &form.actor_id { - Some(id_) => Site::read_from_apub_id(conn, id_).await?.is_none(), + Some(id_) => Site::read_from_apub_id(pool, id_).await?.is_none(), None => true, }; @@ -41,32 +42,32 @@ impl Crud for Site { // initialize languages if site is newly created if is_new_site { // initialize with all languages - SiteLanguage::update(conn, vec![], &site_).await?; + SiteLanguage::update(pool, vec![], &site_).await?; } Ok(site_) } async fn update( - mut conn: impl GetConn, + pool: &DbPool, site_id: SiteId, new_site: &Self::UpdateForm, ) -> Result { + let conn = &mut get_conn(pool).await?; diesel::update(site.find(site_id)) .set(new_site) .get_result::(conn) .await } - async fn delete(mut conn: impl GetConn, site_id: SiteId) -> Result { + async fn delete(pool: &DbPool, site_id: SiteId) -> Result { + let conn = &mut get_conn(pool).await?; diesel::delete(site.find(site_id)).execute(conn).await } } impl Site { - pub async fn read_from_apub_id( - mut conn: impl GetConn, - object_id: &DbUrl, - ) -> Result, Error> { + pub async fn read_from_apub_id(pool: &DbPool, object_id: &DbUrl) -> Result, Error> { + let conn = &mut get_conn(pool).await?; Ok( site .filter(actor_id.eq(object_id)) @@ -78,12 +79,9 @@ impl Site { } // TODO this needs fixed - pub async fn read_remote_sites(mut conn: impl GetConn) -> Result, Error> { - site - .order_by(id) - .offset(1) - .get_results::(conn) - .await + pub async fn read_remote_sites(pool: &DbPool) -> Result, Error> { + let conn = &mut get_conn(pool).await?; + site.order_by(id).offset(1).get_results::(conn).await } /// Instance actor is at the root path, so we simply need to clear the path and other unnecessary diff --git a/crates/db_schema/src/impls/tagline.rs b/crates/db_schema/src/impls/tagline.rs index 37121d3dd..ec985a3c8 100644 --- a/crates/db_schema/src/impls/tagline.rs +++ b/crates/db_schema/src/impls/tagline.rs @@ -2,17 +2,18 @@ use crate::{ newtypes::LocalSiteId, schema::tagline::dsl::{local_site_id, tagline}, source::tagline::{Tagline, TaglineForm}, - utils::GetConn, + utils::{get_conn, DbPool}, }; use diesel::{insert_into, result::Error, ExpressionMethods, QueryDsl}; -use lemmy_db_schema::utils::RunQueryDsl; +use diesel_async::{AsyncPgConnection, RunQueryDsl}; impl Tagline { pub async fn replace( - mut conn: impl GetConn, + pool: &DbPool, for_local_site_id: LocalSiteId, list_content: Option>, ) -> Result, Error> { + let conn = &mut get_conn(pool).await?; if let Some(list) = list_content { conn .build_transaction() @@ -40,12 +41,12 @@ impl Tagline { } } - async fn clear(mut conn: impl GetConn) -> Result { + async fn clear(conn: &mut AsyncPgConnection) -> Result { diesel::delete(tagline).execute(conn).await } async fn get_all_conn( - mut conn: impl GetConn, + conn: &mut AsyncPgConnection, for_local_site_id: LocalSiteId, ) -> Result, Error> { tagline @@ -53,10 +54,8 @@ impl Tagline { .get_results::(conn) .await } - pub async fn get_all( - mut conn: impl GetConn, - for_local_site_id: LocalSiteId, - ) -> Result, Error> { + pub async fn get_all(pool: &DbPool, for_local_site_id: LocalSiteId) -> Result, Error> { + let conn = &mut get_conn(pool).await?; Self::get_all_conn(conn, for_local_site_id).await } } diff --git a/crates/db_schema/src/traits.rs b/crates/db_schema/src/traits.rs index 5c1befe94..12b92b3d9 100644 --- a/crates/db_schema/src/traits.rs +++ b/crates/db_schema/src/traits.rs @@ -1,6 +1,6 @@ use crate::{ newtypes::{CommunityId, DbUrl, PersonId}, - utils::GetConn, + utils::DbPool, }; use diesel::result::Error; @@ -9,21 +9,17 @@ pub trait Crud { type InsertForm; type UpdateForm; type IdType; - async fn create(mut conn: impl GetConn, form: &Self::InsertForm) -> Result + async fn create(pool: &DbPool, form: &Self::InsertForm) -> Result where Self: Sized; - async fn read(mut conn: impl GetConn, id: Self::IdType) -> Result + async fn read(pool: &DbPool, id: Self::IdType) -> Result where Self: Sized; /// when you want to null out a column, you have to send Some(None)), since sending None means you just don't want to update that column. - async fn update( - mut conn: impl GetConn, - id: Self::IdType, - form: &Self::UpdateForm, - ) -> Result + async fn update(pool: &DbPool, id: Self::IdType, form: &Self::UpdateForm) -> Result where Self: Sized; - async fn delete(_conn: impl GetConn, _id: Self::IdType) -> Result + async fn delete(_pool: &DbPool, _id: Self::IdType) -> Result where Self: Sized, Self::IdType: Send, @@ -35,17 +31,17 @@ pub trait Crud { #[async_trait] pub trait Followable { type Form; - async fn follow(mut conn: impl GetConn, form: &Self::Form) -> Result + async fn follow(pool: &DbPool, form: &Self::Form) -> Result where Self: Sized; async fn follow_accepted( - mut conn: impl GetConn, + pool: &DbPool, community_id: CommunityId, person_id: PersonId, ) -> Result where Self: Sized; - async fn unfollow(mut conn: impl GetConn, form: &Self::Form) -> Result + async fn unfollow(pool: &DbPool, form: &Self::Form) -> Result where Self: Sized; } @@ -53,10 +49,10 @@ pub trait Followable { #[async_trait] pub trait Joinable { type Form; - async fn join(mut conn: impl GetConn, form: &Self::Form) -> Result + async fn join(pool: &DbPool, form: &Self::Form) -> Result where Self: Sized; - async fn leave(mut conn: impl GetConn, form: &Self::Form) -> Result + async fn leave(pool: &DbPool, form: &Self::Form) -> Result where Self: Sized; } @@ -65,11 +61,11 @@ pub trait Joinable { pub trait Likeable { type Form; type IdType; - async fn like(mut conn: impl GetConn, form: &Self::Form) -> Result + async fn like(pool: &DbPool, form: &Self::Form) -> Result where Self: Sized; async fn remove( - mut conn: impl GetConn, + pool: &DbPool, person_id: PersonId, item_id: Self::IdType, ) -> Result @@ -80,10 +76,10 @@ pub trait Likeable { #[async_trait] pub trait Bannable { type Form; - async fn ban(mut conn: impl GetConn, form: &Self::Form) -> Result + async fn ban(pool: &DbPool, form: &Self::Form) -> Result where Self: Sized; - async fn unban(mut conn: impl GetConn, form: &Self::Form) -> Result + async fn unban(pool: &DbPool, form: &Self::Form) -> Result where Self: Sized; } @@ -91,10 +87,10 @@ pub trait Bannable { #[async_trait] pub trait Saveable { type Form; - async fn save(mut conn: impl GetConn, form: &Self::Form) -> Result + async fn save(pool: &DbPool, form: &Self::Form) -> Result where Self: Sized; - async fn unsave(mut conn: impl GetConn, form: &Self::Form) -> Result + async fn unsave(pool: &DbPool, form: &Self::Form) -> Result where Self: Sized; } @@ -102,10 +98,10 @@ pub trait Saveable { #[async_trait] pub trait Blockable { type Form; - async fn block(mut conn: impl GetConn, form: &Self::Form) -> Result + async fn block(pool: &DbPool, form: &Self::Form) -> Result where Self: Sized; - async fn unblock(mut conn: impl GetConn, form: &Self::Form) -> Result + async fn unblock(pool: &DbPool, form: &Self::Form) -> Result where Self: Sized; } @@ -113,10 +109,10 @@ pub trait Blockable { #[async_trait] pub trait Readable { type Form; - async fn mark_as_read(mut conn: impl GetConn, form: &Self::Form) -> Result + async fn mark_as_read(pool: &DbPool, form: &Self::Form) -> Result where Self: Sized; - async fn mark_as_unread(mut conn: impl GetConn, form: &Self::Form) -> Result + async fn mark_as_unread(pool: &DbPool, form: &Self::Form) -> Result where Self: Sized; } @@ -125,18 +121,18 @@ pub trait Readable { pub trait Reportable { type Form; type IdType; - async fn report(mut conn: impl GetConn, form: &Self::Form) -> Result + async fn report(pool: &DbPool, form: &Self::Form) -> Result where Self: Sized; async fn resolve( - mut conn: impl GetConn, + pool: &DbPool, report_id: Self::IdType, resolver_id: PersonId, ) -> Result where Self: Sized; async fn unresolve( - mut conn: impl GetConn, + pool: &DbPool, report_id: Self::IdType, resolver_id: PersonId, ) -> Result @@ -153,23 +149,20 @@ pub trait JoinView { #[async_trait] pub trait ApubActor { - async fn read_from_apub_id( - mut conn: impl GetConn, - object_id: &DbUrl, - ) -> Result, Error> + async fn read_from_apub_id(pool: &DbPool, object_id: &DbUrl) -> Result, Error> where Self: Sized; /// - actor_name is the name of the community or user to read. /// - include_deleted, if true, will return communities or users that were deleted/removed async fn read_from_name( - mut conn: impl GetConn, + pool: &DbPool, actor_name: &str, include_deleted: bool, ) -> Result where Self: Sized; async fn read_from_name_and_domain( - mut conn: impl GetConn, + pool: &DbPool, actor_name: &str, protocol_domain: &str, ) -> Result diff --git a/crates/db_schema/src/utils.rs b/crates/db_schema/src/utils.rs index 0af043130..1dc2f9afa 100644 --- a/crates/db_schema/src/utils.rs +++ b/crates/db_schema/src/utils.rs @@ -23,7 +23,6 @@ use diesel_async::{ deadpool::{Object as PooledConnection, Pool}, AsyncDieselConnectionManager, }, - scoped_futures::ScopedBoxFuture, }; use diesel_migrations::EmbeddedMigrations; use futures_util::{future::BoxFuture, FutureExt}; @@ -48,95 +47,6 @@ pub const FETCH_LIMIT_MAX: i64 = 50; const POOL_TIMEOUT: Option = Some(Duration::from_secs(5)); pub type DbPool = Pool; -pub type DbPooledConn = PooledConnection; - -#[async_trait] -pub trait GetConn { - type Conn: std::ops::DerefMut + Send; - - async fn conn(self) -> Result; - - async fn transaction<'a, R, E, F>(&mut self, callback: F) -> Result - where - F: for<'r> FnOnce(&'r mut Self::Conn) -> ScopedBoxFuture<'a, 'r, Result> + Send + 'a, - E: From + Send + 'a, - R: Send + 'a, - { - let conn = self.conn().await?; - conn.transaction(callback).await? - } -} - -#[async_trait] -impl<'a> GetConn for &'a mut AsyncPgConnection { - type Conn = Self; - - async fn conn(self) -> Result { - Ok(self) - } -} - -#[async_trait] -impl<'a> GetConn for &'a DbPool { - type Conn = PooledConnection; - - async fn conn(self) -> Result { - get_conn(self).await - } -} - -#[async_trait] -pub trait RunQueryDsl: diesel_async::RunQueryDsl { - async fn execute<'conn, 'query>(self, conn: Conn) -> Result - where - Self: diesel_async::methods::ExecuteDsl + 'query, - { - Ok(diesel_async::RunQueryDsl::execute(self, &mut conn.conn().await?).await?) - } - async fn load<'query, 'conn, U>(self, conn: Conn) -> Result, DieselError> - where - U: Send, - Self: diesel_async::methods::LoadQuery<'query, Conn::Conn, U> + 'query, - { - Ok(diesel_async::RunQueryDsl::load(self, &mut conn.conn().await?).await?) - } - /* unsued - async fn load_stream<'conn, 'query, U>( - self, - conn: Conn, - ) -> as Future>::Output - where - U: 'conn, - Self: diesel_async::methods::LoadQuery<'query, Conn::Conn, U> + 'query, - { - Ok(diesel_async::RunQueryDsl::load_stream(self, &mut conn.conn().await?).await?) - }*/ - async fn get_result<'query, 'conn, U>(self, conn: Conn) -> Result - where - U: Send + 'conn, - Self: diesel_async::methods::LoadQuery<'query, Conn::Conn, U> + 'query, - { - Ok(diesel_async::RunQueryDsl::get_result(self, &mut conn.conn().await?).await?) - } - async fn get_results<'query, 'conn, U>(self, conn: Conn) -> Result, DieselError> - where - U: Send, - Self: diesel_async::methods::LoadQuery<'query, Conn::Conn, U> + 'query, - { - Ok(diesel_async::RunQueryDsl::get_results(self, &mut conn.conn().await?).await?) - } - async fn first<'query, 'conn, U>(self, conn: Conn) -> Result - where - U: Send + 'conn, - Self: diesel::query_dsl::methods::LimitDsl, - diesel::helper_types::Limit: - diesel_async::methods::LoadQuery<'query, Conn::Conn, U> + Send + 'query, - { - Ok(diesel_async::RunQueryDsl::execute(self, &mut conn.conn().await?).await?) - } -} - -impl RunQueryDsl for T where T: diesel_async::RunQueryDsl {} pub async fn get_conn(pool: &DbPool) -> Result, DieselError> { pool.get().await.map_err(|e| QueryBuilderError(e.into())) @@ -306,7 +216,7 @@ pub fn run_migrations(db_url: &str) { let mut conn = PgConnection::establish(db_url).unwrap_or_else(|e| panic!("Error connecting to {db_url}: {e}")); info!("Running Database migrations (This may take a long time)..."); - let _ = conn + let _ = &mut conn .run_pending_migrations(MIGRATIONS) .unwrap_or_else(|e| panic!("Couldn't run DB Migrations: {e}")); info!("Database migrations complete."); @@ -322,12 +232,6 @@ pub async fn build_db_pool_for_tests() -> DbPool { .expect("db pool missing") } -pub async fn build_db_conn_for_tests() -> DbPooledConn { - get_conn(&build_db_pool_for_tests().await) - .await - .expect("failed to get connection in pool") -} - pub fn get_database_url(settings: Option<&Settings>) -> String { // The env var should override anything in the settings config match get_database_url_from_env() { diff --git a/crates/db_views/src/comment_report_view.rs b/crates/db_views/src/comment_report_view.rs index 5d33cfc35..4a5397b32 100644 --- a/crates/db_views/src/comment_report_view.rs +++ b/crates/db_views/src/comment_report_view.rs @@ -8,6 +8,7 @@ use diesel::{ NullableExpressionMethods, QueryDsl, }; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ aggregates::structs::CommentAggregates, newtypes::{CommentReportId, CommunityId, PersonId}, @@ -30,7 +31,7 @@ use lemmy_db_schema::{ post::Post, }, traits::JoinView, - utils::{limit_and_offset, GetConn, RunQueryDsl}, + utils::{get_conn, limit_and_offset, DbPool}, }; use typed_builder::TypedBuilder; @@ -39,10 +40,12 @@ impl CommentReportView { /// /// * `report_id` - the report id to obtain pub async fn read( - mut conn: impl GetConn, + pool: &DbPool, report_id: CommentReportId, my_person_id: PersonId, ) -> Result { + let conn = &mut get_conn(pool).await?; + let (person_alias_1, person_alias_2) = diesel::alias!(person as person1, person as person2); let res = comment_report::table @@ -93,13 +96,15 @@ impl CommentReportView { /// Returns the current unresolved post report count for the communities you mod pub async fn get_report_count( - mut conn: impl GetConn, + pool: &DbPool, my_person_id: PersonId, admin: bool, community_id: Option, ) -> Result { use diesel::dsl::count; + let conn = &mut get_conn(pool).await?; + let mut query = comment_report::table .inner_join(comment::table) .inner_join(post::table.on(comment::post_id.eq(post::id))) @@ -134,9 +139,9 @@ impl CommentReportView { #[derive(TypedBuilder)] #[builder(field_defaults(default))] -pub struct CommentReportQuery { +pub struct CommentReportQuery<'a> { #[builder(!default)] - conn: Conn, + pool: &'a DbPool, #[builder(!default)] my_person_id: PersonId, #[builder(!default)] @@ -147,9 +152,9 @@ pub struct CommentReportQuery { unresolved_only: Option, } -impl CommentReportQuery { +impl<'a> CommentReportQuery<'a> { pub async fn list(self) -> Result, Error> { - let mut conn = self.conn; + let conn = &mut get_conn(self.pool).await?; let (person_alias_1, person_alias_2) = diesel::alias!(person as person1, person as person2); @@ -280,16 +285,16 @@ mod tests { post::{Post, PostInsertForm}, }, traits::{Crud, Joinable, Reportable}, - utils::build_db_conn_for_tests, + utils::build_db_pool_for_tests, }; use serial_test::serial; #[tokio::test] #[serial] async fn test_crud() { - let mut conn = build_db_conn_for_tests().await; + let pool = &build_db_pool_for_tests().await; - let inserted_instance = Instance::read_or_create(conn, "my_domain.tld".to_string()) + let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()) .await .unwrap(); @@ -299,7 +304,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_timmy = Person::create(conn, &new_person).await.unwrap(); + let inserted_timmy = Person::create(pool, &new_person).await.unwrap(); let new_person_2 = PersonInsertForm::builder() .name("sara_crv".into()) @@ -307,7 +312,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_sara = Person::create(conn, &new_person_2).await.unwrap(); + let inserted_sara = Person::create(pool, &new_person_2).await.unwrap(); // Add a third person, since new ppl can only report something once. let new_person_3 = PersonInsertForm::builder() @@ -316,7 +321,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_jessica = Person::create(conn, &new_person_3).await.unwrap(); + let inserted_jessica = Person::create(pool, &new_person_3).await.unwrap(); let new_community = CommunityInsertForm::builder() .name("test community crv".to_string()) @@ -325,7 +330,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_community = Community::create(conn, &new_community).await.unwrap(); + let inserted_community = Community::create(pool, &new_community).await.unwrap(); // Make timmy a mod let timmy_moderator_form = CommunityModeratorForm { @@ -333,7 +338,7 @@ mod tests { person_id: inserted_timmy.id, }; - let _inserted_moderator = CommunityModerator::join(conn, &timmy_moderator_form) + let _inserted_moderator = CommunityModerator::join(pool, &timmy_moderator_form) .await .unwrap(); @@ -343,7 +348,7 @@ mod tests { .community_id(inserted_community.id) .build(); - let inserted_post = Post::create(conn, &new_post).await.unwrap(); + let inserted_post = Post::create(pool, &new_post).await.unwrap(); let comment_form = CommentInsertForm::builder() .content("A test comment 32".into()) @@ -351,9 +356,7 @@ mod tests { .post_id(inserted_post.id) .build(); - let inserted_comment = Comment::create(conn, &comment_form, None) - .await - .unwrap(); + let inserted_comment = Comment::create(pool, &comment_form, None).await.unwrap(); // sara reports let sara_report_form = CommentReportForm { @@ -363,7 +366,7 @@ mod tests { reason: "from sara".into(), }; - let inserted_sara_report = CommentReport::report(conn, &sara_report_form) + let inserted_sara_report = CommentReport::report(pool, &sara_report_form) .await .unwrap(); @@ -375,16 +378,16 @@ mod tests { reason: "from jessica".into(), }; - let inserted_jessica_report = CommentReport::report(conn, &jessica_report_form) + let inserted_jessica_report = CommentReport::report(pool, &jessica_report_form) .await .unwrap(); - let agg = CommentAggregates::read(conn, inserted_comment.id) + let agg = CommentAggregates::read(pool, inserted_comment.id) .await .unwrap(); let read_jessica_report_view = - CommentReportView::read(conn, inserted_jessica_report.id, inserted_timmy.id) + CommentReportView::read(pool, inserted_jessica_report.id, inserted_timmy.id) .await .unwrap(); let expected_jessica_report_view = CommentReportView { @@ -511,7 +514,7 @@ mod tests { // Do a batch read of timmys reports let reports = CommentReportQuery::builder() - .conn(conn) + .pool(pool) .my_person_id(inserted_timmy.id) .admin(false) .build() @@ -528,18 +531,17 @@ mod tests { ); // Make sure the counts are correct - let report_count = - CommentReportView::get_report_count(conn, inserted_timmy.id, false, None) - .await - .unwrap(); + let report_count = CommentReportView::get_report_count(pool, inserted_timmy.id, false, None) + .await + .unwrap(); assert_eq!(2, report_count); // Try to resolve the report - CommentReport::resolve(conn, inserted_jessica_report.id, inserted_timmy.id) + CommentReport::resolve(pool, inserted_jessica_report.id, inserted_timmy.id) .await .unwrap(); let read_jessica_report_view_after_resolve = - CommentReportView::read(conn, inserted_jessica_report.id, inserted_timmy.id) + CommentReportView::read(pool, inserted_jessica_report.id, inserted_timmy.id) .await .unwrap(); @@ -588,7 +590,7 @@ mod tests { // Do a batch read of timmys reports // It should only show saras, which is unresolved let reports_after_resolve = CommentReportQuery::builder() - .conn(conn) + .pool(pool) .my_person_id(inserted_timmy.id) .admin(false) .unresolved_only(Some(true)) @@ -601,21 +603,17 @@ mod tests { // Make sure the counts are correct let report_count_after_resolved = - CommentReportView::get_report_count(conn, inserted_timmy.id, false, None) + CommentReportView::get_report_count(pool, inserted_timmy.id, false, None) .await .unwrap(); assert_eq!(1, report_count_after_resolved); - Person::delete(conn, inserted_timmy.id).await.unwrap(); - Person::delete(conn, inserted_sara.id).await.unwrap(); - Person::delete(conn, inserted_jessica.id) - .await - .unwrap(); - Community::delete(conn, inserted_community.id) - .await - .unwrap(); - Instance::delete(conn, inserted_instance.id) + Person::delete(pool, inserted_timmy.id).await.unwrap(); + Person::delete(pool, inserted_sara.id).await.unwrap(); + Person::delete(pool, inserted_jessica.id).await.unwrap(); + Community::delete(pool, inserted_community.id) .await .unwrap(); + Instance::delete(pool, inserted_instance.id).await.unwrap(); } } diff --git a/crates/db_views/src/comment_view.rs b/crates/db_views/src/comment_view.rs index 0b3836a0c..f3b1f83a8 100644 --- a/crates/db_views/src/comment_view.rs +++ b/crates/db_views/src/comment_view.rs @@ -8,6 +8,7 @@ use diesel::{ PgTextExpressionMethods, QueryDsl, }; +use diesel_async::RunQueryDsl; use diesel_ltree::{nlevel, subpath, Ltree, LtreeExtensions}; use lemmy_db_schema::{ aggregates::structs::CommentAggregates, @@ -35,7 +36,7 @@ use lemmy_db_schema::{ post::Post, }, traits::JoinView, - utils::{fuzzy_search, limit_and_offset, GetConn, RunQueryDsl}, + utils::{fuzzy_search, get_conn, limit_and_offset, DbPool}, CommentSortType, ListingType, }; @@ -56,10 +57,12 @@ type CommentViewTuple = ( impl CommentView { pub async fn read( - mut conn: impl GetConn, + pool: &DbPool, comment_id: CommentId, my_person_id: Option, ) -> Result { + let conn = &mut get_conn(pool).await?; + // The left join below will return None in this case let person_id_join = my_person_id.unwrap_or(PersonId(-1)); @@ -155,9 +158,9 @@ impl CommentView { #[derive(TypedBuilder)] #[builder(field_defaults(default))] -pub struct CommentQuery<'a, Conn> { +pub struct CommentQuery<'a> { #[builder(!default)] - conn: Conn, + pool: &'a DbPool, listing_type: Option, sort: Option, community_id: Option, @@ -173,9 +176,9 @@ pub struct CommentQuery<'a, Conn> { max_depth: Option, } -impl<'a, Conn: GetConn> CommentQuery<'a, Conn> { +impl<'a> CommentQuery<'a> { pub async fn list(self) -> Result, Error> { - let mut conn = self.conn; + let conn = &mut get_conn(self.pool).await?; // The left join below will return None in this case let person_id_join = self.local_user.map(|l| l.person_id).unwrap_or(PersonId(-1)); @@ -389,6 +392,7 @@ mod tests { CommentSortType, CommentView, Community, + DbPool, LocalUser, Person, PersonBlock, @@ -410,7 +414,7 @@ mod tests { post::PostInsertForm, }, traits::{Blockable, Crud, Likeable}, - utils::{build_db_conn_for_tests, GetConn}, + utils::build_db_pool_for_tests, SubscribedType, }; use serial_test::serial; @@ -427,8 +431,8 @@ mod tests { inserted_community: Community, } - async fn init_data(mut conn: impl GetConn) -> Data { - let inserted_instance = Instance::read_or_create(conn, "my_domain.tld".to_string()) + async fn init_data(pool: &DbPool) -> Data { + let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()) .await .unwrap(); @@ -437,21 +441,19 @@ mod tests { .public_key("pubkey".to_string()) .instance_id(inserted_instance.id) .build(); - let inserted_person = Person::create(conn, &new_person).await.unwrap(); + let inserted_person = Person::create(pool, &new_person).await.unwrap(); let local_user_form = LocalUserInsertForm::builder() .person_id(inserted_person.id) .password_encrypted(String::new()) .build(); - let inserted_local_user = LocalUser::create(conn, &local_user_form) - .await - .unwrap(); + let inserted_local_user = LocalUser::create(pool, &local_user_form).await.unwrap(); let new_person_2 = PersonInsertForm::builder() .name("sara".into()) .public_key("pubkey".to_string()) .instance_id(inserted_instance.id) .build(); - let inserted_person_2 = Person::create(conn, &new_person_2).await.unwrap(); + let inserted_person_2 = Person::create(pool, &new_person_2).await.unwrap(); let new_community = CommunityInsertForm::builder() .name("test community 5".to_string()) @@ -460,7 +462,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_community = Community::create(conn, &new_community).await.unwrap(); + let inserted_community = Community::create(pool, &new_community).await.unwrap(); let new_post = PostInsertForm::builder() .name("A test post 2".into()) @@ -468,10 +470,8 @@ mod tests { .community_id(inserted_community.id) .build(); - let inserted_post = Post::create(conn, &new_post).await.unwrap(); - let english_id = Language::read_id_from_code(conn, Some("en")) - .await - .unwrap(); + let inserted_post = Post::create(pool, &new_post).await.unwrap(); + let english_id = Language::read_id_from_code(pool, Some("en")).await.unwrap(); // Create a comment tree with this hierarchy // 0 @@ -488,9 +488,7 @@ mod tests { .language_id(english_id) .build(); - let inserted_comment_0 = Comment::create(conn, &comment_form_0, None) - .await - .unwrap(); + let inserted_comment_0 = Comment::create(pool, &comment_form_0, None).await.unwrap(); let comment_form_1 = CommentInsertForm::builder() .content("Comment 1, A test blocked comment".into()) @@ -499,14 +497,11 @@ mod tests { .language_id(english_id) .build(); - let inserted_comment_1 = - Comment::create(conn, &comment_form_1, Some(&inserted_comment_0.path)) - .await - .unwrap(); - - let finnish_id = Language::read_id_from_code(conn, Some("fi")) + let inserted_comment_1 = Comment::create(pool, &comment_form_1, Some(&inserted_comment_0.path)) .await .unwrap(); + + let finnish_id = Language::read_id_from_code(pool, Some("fi")).await.unwrap(); let comment_form_2 = CommentInsertForm::builder() .content("Comment 2".into()) .creator_id(inserted_person.id) @@ -514,10 +509,9 @@ mod tests { .language_id(finnish_id) .build(); - let inserted_comment_2 = - Comment::create(conn, &comment_form_2, Some(&inserted_comment_0.path)) - .await - .unwrap(); + let inserted_comment_2 = Comment::create(pool, &comment_form_2, Some(&inserted_comment_0.path)) + .await + .unwrap(); let comment_form_3 = CommentInsertForm::builder() .content("Comment 3".into()) @@ -527,11 +521,11 @@ mod tests { .build(); let _inserted_comment_3 = - Comment::create(conn, &comment_form_3, Some(&inserted_comment_1.path)) + Comment::create(pool, &comment_form_3, Some(&inserted_comment_1.path)) .await .unwrap(); - let polish_id = Language::read_id_from_code(conn, Some("pl")) + let polish_id = Language::read_id_from_code(pool, Some("pl")) .await .unwrap() .unwrap(); @@ -542,10 +536,9 @@ mod tests { .language_id(Some(polish_id)) .build(); - let inserted_comment_4 = - Comment::create(conn, &comment_form_4, Some(&inserted_comment_1.path)) - .await - .unwrap(); + let inserted_comment_4 = Comment::create(pool, &comment_form_4, Some(&inserted_comment_1.path)) + .await + .unwrap(); let comment_form_5 = CommentInsertForm::builder() .content("Comment 5".into()) @@ -554,7 +547,7 @@ mod tests { .build(); let _inserted_comment_5 = - Comment::create(conn, &comment_form_5, Some(&inserted_comment_4.path)) + Comment::create(pool, &comment_form_5, Some(&inserted_comment_4.path)) .await .unwrap(); @@ -563,7 +556,7 @@ mod tests { target_id: inserted_person_2.id, }; - let inserted_block = PersonBlock::block(conn, &timmy_blocks_sara_form) + let inserted_block = PersonBlock::block(pool, &timmy_blocks_sara_form) .await .unwrap(); @@ -582,9 +575,7 @@ mod tests { score: 1, }; - let _inserted_comment_like = CommentLike::like(conn, &comment_like_form) - .await - .unwrap(); + let _inserted_comment_like = CommentLike::like(pool, &comment_like_form).await.unwrap(); Data { inserted_instance, @@ -602,16 +593,16 @@ mod tests { #[tokio::test] #[serial] async fn test_crud() { - let mut conn = build_db_conn_for_tests().await; - let data = init_data(conn).await; + let pool = &build_db_pool_for_tests().await; + let data = init_data(pool).await; - let expected_comment_view_no_person = expected_comment_view(&data, conn).await; + let expected_comment_view_no_person = expected_comment_view(&data, pool).await; let mut expected_comment_view_with_person = expected_comment_view_no_person.clone(); expected_comment_view_with_person.my_vote = Some(1); let read_comment_views_no_person = CommentQuery::builder() - .conn(conn) + .pool(pool) .sort(Some(CommentSortType::Old)) .post_id(Some(data.inserted_post.id)) .build() @@ -625,7 +616,7 @@ mod tests { ); let read_comment_views_with_person = CommentQuery::builder() - .conn(conn) + .pool(pool) .sort(Some(CommentSortType::Old)) .post_id(Some(data.inserted_post.id)) .local_user(Some(&data.inserted_local_user)) @@ -643,7 +634,7 @@ mod tests { assert_eq!(5, read_comment_views_with_person.len()); let read_comment_from_blocked_person = CommentView::read( - conn, + pool, data.inserted_comment_1.id, Some(data.inserted_person.id), ) @@ -653,18 +644,18 @@ mod tests { // Make sure block set the creator blocked assert!(read_comment_from_blocked_person.creator_blocked); - cleanup(data, conn).await; + cleanup(data, pool).await; } #[tokio::test] #[serial] async fn test_comment_tree() { - let mut conn = build_db_conn_for_tests().await; - let data = init_data(conn).await; + let pool = &build_db_pool_for_tests().await; + let data = init_data(pool).await; let top_path = data.inserted_comment_0.path.clone(); let read_comment_views_top_path = CommentQuery::builder() - .conn(conn) + .pool(pool) .post_id(Some(data.inserted_post.id)) .parent_path(Some(top_path)) .build() @@ -674,7 +665,7 @@ mod tests { let child_path = data.inserted_comment_1.path.clone(); let read_comment_views_child_path = CommentQuery::builder() - .conn(conn) + .pool(pool) .post_id(Some(data.inserted_post.id)) .parent_path(Some(child_path)) .build() @@ -695,7 +686,7 @@ mod tests { assert!(!child_comments.contains(&data.inserted_comment_2)); let read_comment_views_top_max_depth = CommentQuery::builder() - .conn(conn) + .pool(pool) .post_id(Some(data.inserted_post.id)) .max_depth(Some(1)) .build() @@ -705,14 +696,14 @@ mod tests { // Make sure a depth limited one only has the top comment assert_eq!( - expected_comment_view(&data, conn).await, + expected_comment_view(&data, pool).await, read_comment_views_top_max_depth[0] ); assert_eq!(1, read_comment_views_top_max_depth.len()); let child_path = data.inserted_comment_1.path.clone(); let read_comment_views_parent_max_depth = CommentQuery::builder() - .conn(conn) + .pool(pool) .post_id(Some(data.inserted_post.id)) .parent_path(Some(child_path)) .max_depth(Some(1)) @@ -729,19 +720,19 @@ mod tests { .eq("Comment 3")); assert_eq!(3, read_comment_views_parent_max_depth.len()); - cleanup(data, conn).await; + cleanup(data, pool).await; } #[tokio::test] #[serial] async fn test_languages() { - let mut conn = build_db_conn_for_tests().await; - let data = init_data(conn).await; + let pool = &build_db_pool_for_tests().await; + let data = init_data(pool).await; // by default, user has all languages enabled and should see all comments // (except from blocked user) let all_languages = CommentQuery::builder() - .conn(conn) + .pool(pool) .local_user(Some(&data.inserted_local_user)) .build() .list() @@ -750,15 +741,15 @@ mod tests { assert_eq!(5, all_languages.len()); // change user lang to finnish, should only show one post in finnish and one undetermined - let finnish_id = Language::read_id_from_code(conn, Some("fi")) + let finnish_id = Language::read_id_from_code(pool, Some("fi")) .await .unwrap() .unwrap(); - LocalUserLanguage::update(conn, vec![finnish_id], data.inserted_local_user.id) + LocalUserLanguage::update(pool, vec![finnish_id], data.inserted_local_user.id) .await .unwrap(); let finnish_comments = CommentQuery::builder() - .conn(conn) + .pool(pool) .local_user(Some(&data.inserted_local_user)) .build() .list() @@ -775,15 +766,11 @@ mod tests { ); // now show all comments with undetermined language (which is the default value) - LocalUserLanguage::update( - conn, - vec![UNDETERMINED_ID], - data.inserted_local_user.id, - ) - .await - .unwrap(); + LocalUserLanguage::update(pool, vec![UNDETERMINED_ID], data.inserted_local_user.id) + .await + .unwrap(); let undetermined_comment = CommentQuery::builder() - .conn(conn) + .pool(pool) .local_user(Some(&data.inserted_local_user)) .build() .list() @@ -791,42 +778,34 @@ mod tests { .unwrap(); assert_eq!(1, undetermined_comment.len()); - cleanup(data, conn).await; + cleanup(data, pool).await; } - async fn cleanup(data: Data, mut conn: impl GetConn) { - CommentLike::remove( - conn, - data.inserted_person.id, - data.inserted_comment_0.id, - ) - .await - .unwrap(); - Comment::delete(conn, data.inserted_comment_0.id) + async fn cleanup(data: Data, pool: &DbPool) { + CommentLike::remove(pool, data.inserted_person.id, data.inserted_comment_0.id) .await .unwrap(); - Comment::delete(conn, data.inserted_comment_1.id) + Comment::delete(pool, data.inserted_comment_0.id) .await .unwrap(); - Post::delete(conn, data.inserted_post.id) + Comment::delete(pool, data.inserted_comment_1.id) .await .unwrap(); - Community::delete(conn, data.inserted_community.id) + Post::delete(pool, data.inserted_post.id).await.unwrap(); + Community::delete(pool, data.inserted_community.id) .await .unwrap(); - Person::delete(conn, data.inserted_person.id) + Person::delete(pool, data.inserted_person.id).await.unwrap(); + Person::delete(pool, data.inserted_person_2.id) .await .unwrap(); - Person::delete(conn, data.inserted_person_2.id) - .await - .unwrap(); - Instance::delete(conn, data.inserted_instance.id) + Instance::delete(pool, data.inserted_instance.id) .await .unwrap(); } - async fn expected_comment_view(data: &Data, mut conn: impl GetConn) -> CommentView { - let agg = CommentAggregates::read(conn, data.inserted_comment_0.id) + async fn expected_comment_view(data: &Data, pool: &DbPool) -> CommentView { + let agg = CommentAggregates::read(pool, data.inserted_comment_0.id) .await .unwrap(); CommentView { diff --git a/crates/db_views/src/custom_emoji_view.rs b/crates/db_views/src/custom_emoji_view.rs index e382227e3..66d583e32 100644 --- a/crates/db_views/src/custom_emoji_view.rs +++ b/crates/db_views/src/custom_emoji_view.rs @@ -1,17 +1,19 @@ use crate::structs::CustomEmojiView; use diesel::{result::Error, ExpressionMethods, JoinOnDsl, NullableExpressionMethods, QueryDsl}; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ newtypes::{CustomEmojiId, LocalSiteId}, schema::{custom_emoji, custom_emoji_keyword}, source::{custom_emoji::CustomEmoji, custom_emoji_keyword::CustomEmojiKeyword}, - utils::{GetConn, RunQueryDsl}, + utils::{get_conn, DbPool}, }; use std::collections::HashMap; type CustomEmojiTuple = (CustomEmoji, Option); impl CustomEmojiView { - pub async fn get(mut conn: impl GetConn, emoji_id: CustomEmojiId) -> Result { + pub async fn get(pool: &DbPool, emoji_id: CustomEmojiId) -> Result { + let conn = &mut get_conn(pool).await?; let emojis = custom_emoji::table .find(emoji_id) .left_join( @@ -33,10 +35,8 @@ impl CustomEmojiView { } } - pub async fn get_all( - mut conn: impl GetConn, - for_local_site_id: LocalSiteId, - ) -> Result, Error> { + pub async fn get_all(pool: &DbPool, for_local_site_id: LocalSiteId) -> Result, Error> { + let conn = &mut get_conn(pool).await?; let emojis = custom_emoji::table .filter(custom_emoji::local_site_id.eq(for_local_site_id)) .left_join( diff --git a/crates/db_views/src/local_user_view.rs b/crates/db_views/src/local_user_view.rs index 8950fd2d0..f37986cc9 100644 --- a/crates/db_views/src/local_user_view.rs +++ b/crates/db_views/src/local_user_view.rs @@ -1,18 +1,21 @@ use crate::structs::LocalUserView; use diesel::{result::Error, BoolExpressionMethods, ExpressionMethods, JoinOnDsl, QueryDsl}; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ aggregates::structs::PersonAggregates, newtypes::{LocalUserId, PersonId}, schema::{local_user, person, person_aggregates}, source::{local_user::LocalUser, person::Person}, traits::JoinView, - utils::{functions::lower, GetConn, RunQueryDsl}, + utils::{functions::lower, get_conn, DbPool}, }; type LocalUserViewTuple = (LocalUser, Person, PersonAggregates); impl LocalUserView { - pub async fn read(mut conn: impl GetConn, local_user_id: LocalUserId) -> Result { + pub async fn read(pool: &DbPool, local_user_id: LocalUserId) -> Result { + let conn = &mut get_conn(pool).await?; + let (local_user, person, counts) = local_user::table .find(local_user_id) .inner_join(person::table) @@ -31,7 +34,8 @@ impl LocalUserView { }) } - pub async fn read_person(mut conn: impl GetConn, person_id: PersonId) -> Result { + pub async fn read_person(pool: &DbPool, person_id: PersonId) -> Result { + let conn = &mut get_conn(pool).await?; let (local_user, person, counts) = local_user::table .filter(person::id.eq(person_id)) .inner_join(person::table) @@ -50,7 +54,8 @@ impl LocalUserView { }) } - pub async fn read_from_name(mut conn: impl GetConn, name: &str) -> Result { + pub async fn read_from_name(pool: &DbPool, name: &str) -> Result { + let conn = &mut get_conn(pool).await?; let (local_user, person, counts) = local_user::table .filter(lower(person::name).eq(name.to_lowercase())) .inner_join(person::table) @@ -69,10 +74,8 @@ impl LocalUserView { }) } - pub async fn find_by_email_or_name( - mut conn: impl GetConn, - name_or_email: &str, - ) -> Result { + pub async fn find_by_email_or_name(pool: &DbPool, name_or_email: &str) -> Result { + let conn = &mut get_conn(pool).await?; let (local_user, person, counts) = local_user::table .inner_join(person::table) .inner_join(person_aggregates::table.on(person::id.eq(person_aggregates::person_id))) @@ -95,7 +98,8 @@ impl LocalUserView { }) } - pub async fn find_by_email(mut conn: impl GetConn, from_email: &str) -> Result { + pub async fn find_by_email(pool: &DbPool, from_email: &str) -> Result { + let conn = &mut get_conn(pool).await?; let (local_user, person, counts) = local_user::table .inner_join(person::table) .inner_join(person_aggregates::table.on(person::id.eq(person_aggregates::person_id))) @@ -114,7 +118,8 @@ impl LocalUserView { }) } - pub async fn list_admins_with_emails(mut conn: impl GetConn) -> Result, Error> { + pub async fn list_admins_with_emails(pool: &DbPool) -> Result, Error> { + let conn = &mut get_conn(pool).await?; let res = local_user::table .filter(person::admin.eq(true)) .filter(local_user::email.is_not_null()) diff --git a/crates/db_views/src/post_report_view.rs b/crates/db_views/src/post_report_view.rs index 70282f256..19822c795 100644 --- a/crates/db_views/src/post_report_view.rs +++ b/crates/db_views/src/post_report_view.rs @@ -7,6 +7,7 @@ use diesel::{ NullableExpressionMethods, QueryDsl, }; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ aggregates::structs::PostAggregates, newtypes::{CommunityId, PersonId, PostReportId}, @@ -27,7 +28,7 @@ use lemmy_db_schema::{ post_report::PostReport, }, traits::JoinView, - utils::{limit_and_offset, GetConn, RunQueryDsl}, + utils::{get_conn, limit_and_offset, DbPool}, }; use typed_builder::TypedBuilder; @@ -48,10 +49,11 @@ impl PostReportView { /// /// * `report_id` - the report id to obtain pub async fn read( - mut conn: impl GetConn, + pool: &DbPool, report_id: PostReportId, my_person_id: PersonId, ) -> Result { + let conn = &mut get_conn(pool).await?; let (person_alias_1, person_alias_2) = diesel::alias!(person as person1, person as person2); let ( @@ -119,12 +121,13 @@ impl PostReportView { /// returns the current unresolved post report count for the communities you mod pub async fn get_report_count( - mut conn: impl GetConn, + pool: &DbPool, my_person_id: PersonId, admin: bool, community_id: Option, ) -> Result { use diesel::dsl::count; + let conn = &mut get_conn(pool).await?; let mut query = post_report::table .inner_join(post::table) .filter(post_report::resolved.eq(false)) @@ -158,9 +161,9 @@ impl PostReportView { #[derive(TypedBuilder)] #[builder(field_defaults(default))] -pub struct PostReportQuery { +pub struct PostReportQuery<'a> { #[builder(!default)] - conn: Conn, + pool: &'a DbPool, #[builder(!default)] my_person_id: PersonId, #[builder(!default)] @@ -171,9 +174,9 @@ pub struct PostReportQuery { unresolved_only: Option, } -impl PostReportQuery { +impl<'a> PostReportQuery<'a> { pub async fn list(self) -> Result, Error> { - let mut conn = self.conn; + let conn = &mut get_conn(self.pool).await?; let (person_alias_1, person_alias_2) = diesel::alias!(person as person1, person as person2); let mut query = post_report::table @@ -277,16 +280,16 @@ mod tests { post_report::{PostReport, PostReportForm}, }, traits::{Crud, Joinable, Reportable}, - utils::build_db_conn_for_tests, + utils::build_db_pool_for_tests, }; use serial_test::serial; #[tokio::test] #[serial] async fn test_crud() { - let mut conn = build_db_conn_for_tests().await; + let pool = &build_db_pool_for_tests().await; - let inserted_instance = Instance::read_or_create(conn, "my_domain.tld".to_string()) + let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()) .await .unwrap(); @@ -296,7 +299,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_timmy = Person::create(conn, &new_person).await.unwrap(); + let inserted_timmy = Person::create(pool, &new_person).await.unwrap(); let new_person_2 = PersonInsertForm::builder() .name("sara_prv".into()) @@ -304,7 +307,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_sara = Person::create(conn, &new_person_2).await.unwrap(); + let inserted_sara = Person::create(pool, &new_person_2).await.unwrap(); // Add a third person, since new ppl can only report something once. let new_person_3 = PersonInsertForm::builder() @@ -313,7 +316,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_jessica = Person::create(conn, &new_person_3).await.unwrap(); + let inserted_jessica = Person::create(pool, &new_person_3).await.unwrap(); let new_community = CommunityInsertForm::builder() .name("test community prv".to_string()) @@ -322,7 +325,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_community = Community::create(conn, &new_community).await.unwrap(); + let inserted_community = Community::create(pool, &new_community).await.unwrap(); // Make timmy a mod let timmy_moderator_form = CommunityModeratorForm { @@ -330,7 +333,7 @@ mod tests { person_id: inserted_timmy.id, }; - let _inserted_moderator = CommunityModerator::join(conn, &timmy_moderator_form) + let _inserted_moderator = CommunityModerator::join(pool, &timmy_moderator_form) .await .unwrap(); @@ -340,7 +343,7 @@ mod tests { .community_id(inserted_community.id) .build(); - let inserted_post = Post::create(conn, &new_post).await.unwrap(); + let inserted_post = Post::create(pool, &new_post).await.unwrap(); // sara reports let sara_report_form = PostReportForm { @@ -352,9 +355,7 @@ mod tests { reason: "from sara".into(), }; - let inserted_sara_report = PostReport::report(conn, &sara_report_form) - .await - .unwrap(); + let inserted_sara_report = PostReport::report(pool, &sara_report_form).await.unwrap(); // jessica reports let jessica_report_form = PostReportForm { @@ -366,16 +367,14 @@ mod tests { reason: "from jessica".into(), }; - let inserted_jessica_report = PostReport::report(conn, &jessica_report_form) + let inserted_jessica_report = PostReport::report(pool, &jessica_report_form) .await .unwrap(); - let agg = PostAggregates::read(conn, inserted_post.id) - .await - .unwrap(); + let agg = PostAggregates::read(pool, inserted_post.id).await.unwrap(); let read_jessica_report_view = - PostReportView::read(conn, inserted_jessica_report.id, inserted_timmy.id) + PostReportView::read(pool, inserted_jessica_report.id, inserted_timmy.id) .await .unwrap(); let expected_jessica_report_view = PostReportView { @@ -507,7 +506,7 @@ mod tests { // Do a batch read of timmys reports let reports = PostReportQuery::builder() - .conn(conn) + .pool(pool) .my_person_id(inserted_timmy.id) .admin(false) .build() @@ -524,17 +523,17 @@ mod tests { ); // Make sure the counts are correct - let report_count = PostReportView::get_report_count(conn, inserted_timmy.id, false, None) + let report_count = PostReportView::get_report_count(pool, inserted_timmy.id, false, None) .await .unwrap(); assert_eq!(2, report_count); // Try to resolve the report - PostReport::resolve(conn, inserted_jessica_report.id, inserted_timmy.id) + PostReport::resolve(pool, inserted_jessica_report.id, inserted_timmy.id) .await .unwrap(); let read_jessica_report_view_after_resolve = - PostReportView::read(conn, inserted_jessica_report.id, inserted_timmy.id) + PostReportView::read(pool, inserted_jessica_report.id, inserted_timmy.id) .await .unwrap(); @@ -581,7 +580,7 @@ mod tests { // Do a batch read of timmys reports // It should only show saras, which is unresolved let reports_after_resolve = PostReportQuery::builder() - .conn(conn) + .pool(pool) .my_person_id(inserted_timmy.id) .admin(false) .unresolved_only(Some(true)) @@ -593,21 +592,17 @@ mod tests { // Make sure the counts are correct let report_count_after_resolved = - PostReportView::get_report_count(conn, inserted_timmy.id, false, None) + PostReportView::get_report_count(pool, inserted_timmy.id, false, None) .await .unwrap(); assert_eq!(1, report_count_after_resolved); - Person::delete(conn, inserted_timmy.id).await.unwrap(); - Person::delete(conn, inserted_sara.id).await.unwrap(); - Person::delete(conn, inserted_jessica.id) - .await - .unwrap(); - Community::delete(conn, inserted_community.id) - .await - .unwrap(); - Instance::delete(conn, inserted_instance.id) + Person::delete(pool, inserted_timmy.id).await.unwrap(); + Person::delete(pool, inserted_sara.id).await.unwrap(); + Person::delete(pool, inserted_jessica.id).await.unwrap(); + Community::delete(pool, inserted_community.id) .await .unwrap(); + Instance::delete(pool, inserted_instance.id).await.unwrap(); } } diff --git a/crates/db_views/src/post_view.rs b/crates/db_views/src/post_view.rs index 8a1009c23..d1e974d8a 100644 --- a/crates/db_views/src/post_view.rs +++ b/crates/db_views/src/post_view.rs @@ -13,6 +13,7 @@ use diesel::{ PgTextExpressionMethods, QueryDsl, }; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ aggregates::structs::PostAggregates, newtypes::{CommunityId, LocalUserId, PersonId, PostId}, @@ -39,7 +40,7 @@ use lemmy_db_schema::{ post::{Post, PostRead, PostSaved}, }, traits::JoinView, - utils::{fuzzy_search, limit_and_offset, GetConn, RunQueryDsl}, + utils::{fuzzy_search, get_conn, limit_and_offset, DbPool}, ListingType, SortType, }; @@ -64,11 +65,13 @@ sql_function!(fn coalesce(x: sql_types::Nullable, y: sql_type impl PostView { pub async fn read( - mut conn: impl GetConn, + pool: &DbPool, post_id: PostId, my_person_id: Option, is_mod_or_admin: Option, ) -> Result { + let conn = &mut get_conn(pool).await?; + // The left join below will return None in this case let person_id_join = my_person_id.unwrap_or(PersonId(-1)); let mut query = post::table @@ -192,9 +195,9 @@ impl PostView { #[derive(TypedBuilder)] #[builder(field_defaults(default))] -pub struct PostQuery<'a, Conn> { +pub struct PostQuery<'a> { #[builder(!default)] - conn: Conn, + pool: &'a DbPool, listing_type: Option, sort: Option, creator_id: Option, @@ -209,9 +212,9 @@ pub struct PostQuery<'a, Conn> { limit: Option, } -impl<'a, Conn: GetConn> PostQuery<'a, Conn> { +impl<'a> PostQuery<'a> { pub async fn list(self) -> Result, Error> { - let mut conn = self.conn; + let conn = &mut get_conn(self.pool).await?; // The left join below will return None in this case let person_id_join = self.local_user.map(|l| l.person_id).unwrap_or(PersonId(-1)); @@ -491,7 +494,7 @@ mod tests { post::{Post, PostInsertForm, PostLike, PostLikeForm, PostUpdateForm}, }, traits::{Blockable, Crud, Likeable}, - utils::{build_db_conn_for_tests, GetConn}, + utils::{build_db_pool_for_tests, DbPool}, SortType, SubscribedType, }; @@ -507,8 +510,8 @@ mod tests { inserted_post: Post, } - async fn init_data(mut conn: impl GetConn) -> Data { - let inserted_instance = Instance::read_or_create(conn, "my_domain.tld".to_string()) + async fn init_data(pool: &DbPool) -> Data { + let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()) .await .unwrap(); @@ -520,15 +523,13 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_person = Person::create(conn, &new_person).await.unwrap(); + let inserted_person = Person::create(pool, &new_person).await.unwrap(); let local_user_form = LocalUserInsertForm::builder() .person_id(inserted_person.id) .password_encrypted(String::new()) .build(); - let inserted_local_user = LocalUser::create(conn, &local_user_form) - .await - .unwrap(); + let inserted_local_user = LocalUser::create(pool, &local_user_form).await.unwrap(); let new_bot = PersonInsertForm::builder() .name("mybot".to_string()) @@ -537,7 +538,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_bot = Person::create(conn, &new_bot).await.unwrap(); + let inserted_bot = Person::create(pool, &new_bot).await.unwrap(); let new_community = CommunityInsertForm::builder() .name("test_community_3".to_string()) @@ -546,7 +547,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_community = Community::create(conn, &new_community).await.unwrap(); + let inserted_community = Community::create(pool, &new_community).await.unwrap(); // Test a person block, make sure the post query doesn't include their post let blocked_person = PersonInsertForm::builder() @@ -555,7 +556,7 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_blocked_person = Person::create(conn, &blocked_person).await.unwrap(); + let inserted_blocked_person = Person::create(pool, &blocked_person).await.unwrap(); let post_from_blocked_person = PostInsertForm::builder() .name("blocked_person_post".to_string()) @@ -564,9 +565,7 @@ mod tests { .language_id(Some(LanguageId(1))) .build(); - Post::create(conn, &post_from_blocked_person) - .await - .unwrap(); + Post::create(pool, &post_from_blocked_person).await.unwrap(); // block that person let person_block = PersonBlockForm { @@ -574,7 +573,7 @@ mod tests { target_id: inserted_blocked_person.id, }; - PersonBlock::block(conn, &person_block).await.unwrap(); + PersonBlock::block(pool, &person_block).await.unwrap(); // A sample post let new_post = PostInsertForm::builder() @@ -584,7 +583,7 @@ mod tests { .language_id(Some(LanguageId(47))) .build(); - let inserted_post = Post::create(conn, &new_post).await.unwrap(); + let inserted_post = Post::create(pool, &new_post).await.unwrap(); let new_bot_post = PostInsertForm::builder() .name("test bot post".to_string()) @@ -592,7 +591,7 @@ mod tests { .community_id(inserted_community.id) .build(); - let _inserted_bot_post = Post::create(conn, &new_bot_post).await.unwrap(); + let _inserted_bot_post = Post::create(pool, &new_bot_post).await.unwrap(); Data { inserted_instance, @@ -608,19 +607,19 @@ mod tests { #[tokio::test] #[serial] async fn post_listing_with_person() { - let mut conn = build_db_conn_for_tests().await; - let data = init_data(conn).await; + let pool = &build_db_pool_for_tests().await; + let data = init_data(pool).await; let local_user_form = LocalUserUpdateForm::builder() .show_bot_accounts(Some(false)) .build(); let inserted_local_user = - LocalUser::update(conn, data.inserted_local_user.id, &local_user_form) + LocalUser::update(pool, data.inserted_local_user.id, &local_user_form) .await .unwrap(); let read_post_listing = PostQuery::builder() - .conn(conn) + .pool(pool) .sort(Some(SortType::New)) .community_id(Some(data.inserted_community.id)) .local_user(Some(&inserted_local_user)) @@ -630,7 +629,7 @@ mod tests { .unwrap(); let post_listing_single_with_person = PostView::read( - conn, + pool, data.inserted_post.id, Some(data.inserted_person.id), None, @@ -638,7 +637,7 @@ mod tests { .await .unwrap(); - let mut expected_post_listing_with_user = expected_post_view(&data, conn).await; + let mut expected_post_listing_with_user = expected_post_view(&data, pool).await; // Should be only one person, IE the bot post, and blocked should be missing assert_eq!(1, read_post_listing.len()); @@ -654,12 +653,12 @@ mod tests { .show_bot_accounts(Some(true)) .build(); let inserted_local_user = - LocalUser::update(conn, data.inserted_local_user.id, &local_user_form) + LocalUser::update(pool, data.inserted_local_user.id, &local_user_form) .await .unwrap(); let post_listings_with_bots = PostQuery::builder() - .conn(conn) + .pool(pool) .sort(Some(SortType::New)) .community_id(Some(data.inserted_community.id)) .local_user(Some(&inserted_local_user)) @@ -670,17 +669,17 @@ mod tests { // should include bot post which has "undetermined" language assert_eq!(2, post_listings_with_bots.len()); - cleanup(data, conn).await; + cleanup(data, pool).await; } #[tokio::test] #[serial] async fn post_listing_no_person() { - let mut conn = build_db_conn_for_tests().await; - let data = init_data(conn).await; + let pool = &build_db_pool_for_tests().await; + let data = init_data(pool).await; let read_post_listing_multiple_no_person = PostQuery::builder() - .conn(conn) + .pool(pool) .sort(Some(SortType::New)) .community_id(Some(data.inserted_community.id)) .build() @@ -689,11 +688,11 @@ mod tests { .unwrap(); let read_post_listing_single_no_person = - PostView::read(conn, data.inserted_post.id, None, None) + PostView::read(pool, data.inserted_post.id, None, None) .await .unwrap(); - let expected_post_listing_no_person = expected_post_view(&data, conn).await; + let expected_post_listing_no_person = expected_post_view(&data, pool).await; // Should be 2 posts, with the bot post, and the blocked assert_eq!(3, read_post_listing_multiple_no_person.len()); @@ -707,25 +706,23 @@ mod tests { read_post_listing_single_no_person ); - cleanup(data, conn).await; + cleanup(data, pool).await; } #[tokio::test] #[serial] async fn post_listing_block_community() { - let mut conn = build_db_conn_for_tests().await; - let data = init_data(conn).await; + let pool = &build_db_pool_for_tests().await; + let data = init_data(pool).await; let community_block = CommunityBlockForm { person_id: data.inserted_person.id, community_id: data.inserted_community.id, }; - CommunityBlock::block(conn, &community_block) - .await - .unwrap(); + CommunityBlock::block(pool, &community_block).await.unwrap(); let read_post_listings_with_person_after_block = PostQuery::builder() - .conn(conn) + .pool(pool) .sort(Some(SortType::New)) .community_id(Some(data.inserted_community.id)) .local_user(Some(&data.inserted_local_user)) @@ -736,17 +733,17 @@ mod tests { // Should be 0 posts after the community block assert_eq!(0, read_post_listings_with_person_after_block.len()); - CommunityBlock::unblock(conn, &community_block) + CommunityBlock::unblock(pool, &community_block) .await .unwrap(); - cleanup(data, conn).await; + cleanup(data, pool).await; } #[tokio::test] #[serial] async fn post_listing_like() { - let mut conn = build_db_conn_for_tests().await; - let data = init_data(conn).await; + let pool = &build_db_pool_for_tests().await; + let data = init_data(pool).await; let post_like_form = PostLikeForm { post_id: data.inserted_post.id, @@ -754,7 +751,7 @@ mod tests { score: 1, }; - let inserted_post_like = PostLike::like(conn, &post_like_form).await.unwrap(); + let inserted_post_like = PostLike::like(pool, &post_like_form).await.unwrap(); let expected_post_like = PostLike { id: inserted_post_like.id, @@ -766,7 +763,7 @@ mod tests { assert_eq!(expected_post_like, inserted_post_like); let post_listing_single_with_person = PostView::read( - conn, + pool, data.inserted_post.id, Some(data.inserted_person.id), None, @@ -774,7 +771,7 @@ mod tests { .await .unwrap(); - let mut expected_post_with_upvote = expected_post_view(&data, conn).await; + let mut expected_post_with_upvote = expected_post_view(&data, pool).await; expected_post_with_upvote.my_vote = Some(1); expected_post_with_upvote.counts.score = 1; expected_post_with_upvote.counts.upvotes = 1; @@ -784,12 +781,12 @@ mod tests { .show_bot_accounts(Some(false)) .build(); let inserted_local_user = - LocalUser::update(conn, data.inserted_local_user.id, &local_user_form) + LocalUser::update(pool, data.inserted_local_user.id, &local_user_form) .await .unwrap(); let read_post_listing = PostQuery::builder() - .conn(conn) + .pool(pool) .sort(Some(SortType::New)) .community_id(Some(data.inserted_community.id)) .local_user(Some(&inserted_local_user)) @@ -801,20 +798,20 @@ mod tests { assert_eq!(expected_post_with_upvote, read_post_listing[0]); - let like_removed = PostLike::remove(conn, data.inserted_person.id, data.inserted_post.id) + let like_removed = PostLike::remove(pool, data.inserted_person.id, data.inserted_post.id) .await .unwrap(); assert_eq!(1, like_removed); - cleanup(data, conn).await; + cleanup(data, pool).await; } #[tokio::test] #[serial] async fn post_listing_person_language() { - let mut conn = build_db_conn_for_tests().await; - let data = init_data(conn).await; + let pool = &build_db_pool_for_tests().await; + let data = init_data(pool).await; - let spanish_id = Language::read_id_from_code(conn, Some("es")) + let spanish_id = Language::read_id_from_code(pool, Some("es")) .await .unwrap() .unwrap(); @@ -825,10 +822,10 @@ mod tests { .language_id(Some(spanish_id)) .build(); - Post::create(conn, &post_spanish).await.unwrap(); + Post::create(pool, &post_spanish).await.unwrap(); let post_listings_all = PostQuery::builder() - .conn(conn) + .pool(pool) .sort(Some(SortType::New)) .local_user(Some(&data.inserted_local_user)) .build() @@ -839,16 +836,16 @@ mod tests { // no language filters specified, all posts should be returned assert_eq!(3, post_listings_all.len()); - let french_id = Language::read_id_from_code(conn, Some("fr")) + let french_id = Language::read_id_from_code(pool, Some("fr")) .await .unwrap() .unwrap(); - LocalUserLanguage::update(conn, vec![french_id], data.inserted_local_user.id) + LocalUserLanguage::update(pool, vec![french_id], data.inserted_local_user.id) .await .unwrap(); let post_listing_french = PostQuery::builder() - .conn(conn) + .pool(pool) .sort(Some(SortType::New)) .local_user(Some(&data.inserted_local_user)) .build() @@ -863,14 +860,14 @@ mod tests { .any(|p| p.post.language_id == french_id)); LocalUserLanguage::update( - conn, + pool, vec![french_id, UNDETERMINED_ID], data.inserted_local_user.id, ) .await .unwrap(); let post_listings_french_und = PostQuery::builder() - .conn(conn) + .pool(pool) .sort(Some(SortType::New)) .local_user(Some(&data.inserted_local_user)) .build() @@ -886,18 +883,18 @@ mod tests { ); assert_eq!(french_id, post_listings_french_und[1].post.language_id); - cleanup(data, conn).await; + cleanup(data, pool).await; } #[tokio::test] #[serial] async fn post_listings_deleted() { - let mut conn = build_db_conn_for_tests().await; - let data = init_data(conn).await; + let pool = &build_db_pool_for_tests().await; + let data = init_data(pool).await; // Delete the post Post::update( - conn, + pool, data.inserted_post.id, &PostUpdateForm::builder().deleted(Some(true)).build(), ) @@ -906,7 +903,7 @@ mod tests { // Make sure you don't see the deleted post in the results let post_listings_no_admin = PostQuery::builder() - .conn(conn) + .pool(pool) .sort(Some(SortType::New)) .local_user(Some(&data.inserted_local_user)) .is_mod_or_admin(Some(false)) @@ -919,7 +916,7 @@ mod tests { // Make sure they see both let post_listings_is_admin = PostQuery::builder() - .conn(conn) + .pool(pool) .sort(Some(SortType::New)) .local_user(Some(&data.inserted_local_user)) .is_mod_or_admin(Some(true)) @@ -930,40 +927,32 @@ mod tests { assert_eq!(2, post_listings_is_admin.len()); - cleanup(data, conn).await; + cleanup(data, pool).await; } - async fn cleanup(data: Data, mut conn: impl GetConn) { - let num_deleted = Post::delete(conn, data.inserted_post.id) + async fn cleanup(data: Data, pool: &DbPool) { + let num_deleted = Post::delete(pool, data.inserted_post.id).await.unwrap(); + Community::delete(pool, data.inserted_community.id) .await .unwrap(); - Community::delete(conn, data.inserted_community.id) + Person::delete(pool, data.inserted_person.id).await.unwrap(); + Person::delete(pool, data.inserted_bot.id).await.unwrap(); + Person::delete(pool, data.inserted_blocked_person.id) .await .unwrap(); - Person::delete(conn, data.inserted_person.id) - .await - .unwrap(); - Person::delete(conn, data.inserted_bot.id) - .await - .unwrap(); - Person::delete(conn, data.inserted_blocked_person.id) - .await - .unwrap(); - Instance::delete(conn, data.inserted_instance.id) + Instance::delete(pool, data.inserted_instance.id) .await .unwrap(); assert_eq!(1, num_deleted); } - async fn expected_post_view(data: &Data, mut conn: impl GetConn) -> PostView { + async fn expected_post_view(data: &Data, pool: &DbPool) -> PostView { let (inserted_person, inserted_community, inserted_post) = ( &data.inserted_person, &data.inserted_community, &data.inserted_post, ); - let agg = PostAggregates::read(conn, inserted_post.id) - .await - .unwrap(); + let agg = PostAggregates::read(pool, inserted_post.id).await.unwrap(); PostView { post: Post { diff --git a/crates/db_views/src/private_message_report_view.rs b/crates/db_views/src/private_message_report_view.rs index ea3524365..2bcad6f83 100644 --- a/crates/db_views/src/private_message_report_view.rs +++ b/crates/db_views/src/private_message_report_view.rs @@ -1,5 +1,6 @@ use crate::structs::PrivateMessageReportView; use diesel::{result::Error, ExpressionMethods, JoinOnDsl, NullableExpressionMethods, QueryDsl}; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ newtypes::PrivateMessageReportId, schema::{person, private_message, private_message_report}, @@ -9,7 +10,7 @@ use lemmy_db_schema::{ private_message_report::PrivateMessageReport, }, traits::JoinView, - utils::{limit_and_offset, GetConn, RunQueryDsl}, + utils::{get_conn, limit_and_offset, DbPool}, }; use typed_builder::TypedBuilder; @@ -25,10 +26,8 @@ impl PrivateMessageReportView { /// returns the PrivateMessageReportView for the provided report_id /// /// * `report_id` - the report id to obtain - pub async fn read( - mut conn: impl GetConn, - report_id: PrivateMessageReportId, - ) -> Result { + pub async fn read(pool: &DbPool, report_id: PrivateMessageReportId) -> Result { + let conn = &mut get_conn(pool).await?; let (person_alias_1, person_alias_2) = diesel::alias!(person as person1, person as person2); let (private_message_report, private_message, private_message_creator, creator, resolver) = @@ -65,8 +64,9 @@ impl PrivateMessageReportView { } /// Returns the current unresolved post report count for the communities you mod - pub async fn get_report_count(mut conn: impl GetConn) -> Result { + pub async fn get_report_count(pool: &DbPool) -> Result { use diesel::dsl::count; + let conn = &mut get_conn(pool).await?; private_message_report::table .inner_join(private_message::table) @@ -80,17 +80,17 @@ impl PrivateMessageReportView { #[derive(TypedBuilder)] #[builder(field_defaults(default))] -pub struct PrivateMessageReportQuery { +pub struct PrivateMessageReportQuery<'a> { #[builder(!default)] - conn: Conn, + pool: &'a DbPool, page: Option, limit: Option, unresolved_only: Option, } -impl PrivateMessageReportQuery { +impl<'a> PrivateMessageReportQuery<'a> { pub async fn list(self) -> Result, Error> { - let mut conn = self.conn; + let conn = &mut get_conn(self.pool).await?; let (person_alias_1, person_alias_2) = diesel::alias!(person as person1, person as person2); let mut query = private_message_report::table @@ -123,9 +123,7 @@ impl PrivateMessageReportQuery { .limit(limit) .offset(offset); - let res = query - .load::(conn) - .await?; + let res = query.load::(conn).await?; Ok( res @@ -160,16 +158,16 @@ mod tests { private_message_report::{PrivateMessageReport, PrivateMessageReportForm}, }, traits::{Crud, Reportable}, - utils::build_db_conn_for_tests, + utils::build_db_pool_for_tests, }; use serial_test::serial; #[tokio::test] #[serial] async fn test_crud() { - let mut conn = build_db_conn_for_tests().await; + let pool = &build_db_pool_for_tests().await; - let inserted_instance = Instance::read_or_create(conn, "my_domain.tld".to_string()) + let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()) .await .unwrap(); @@ -178,14 +176,14 @@ mod tests { .public_key("pubkey".to_string()) .instance_id(inserted_instance.id) .build(); - let inserted_timmy = Person::create(conn, &new_person_1).await.unwrap(); + let inserted_timmy = Person::create(pool, &new_person_1).await.unwrap(); let new_person_2 = PersonInsertForm::builder() .name("jessica_mrv".into()) .public_key("pubkey".to_string()) .instance_id(inserted_instance.id) .build(); - let inserted_jessica = Person::create(conn, &new_person_2).await.unwrap(); + let inserted_jessica = Person::create(pool, &new_person_2).await.unwrap(); // timmy sends private message to jessica let pm_form = PrivateMessageInsertForm::builder() @@ -193,7 +191,7 @@ mod tests { .recipient_id(inserted_jessica.id) .content("something offensive".to_string()) .build(); - let pm = PrivateMessage::create(conn, &pm_form).await.unwrap(); + let pm = PrivateMessage::create(pool, &pm_form).await.unwrap(); // jessica reports private message let pm_report_form = PrivateMessageReportForm { @@ -202,12 +200,12 @@ mod tests { private_message_id: pm.id, reason: "its offensive".to_string(), }; - let pm_report = PrivateMessageReport::report(conn, &pm_report_form) + let pm_report = PrivateMessageReport::report(pool, &pm_report_form) .await .unwrap(); let reports = PrivateMessageReportQuery::builder() - .conn(conn) + .pool(pool) .build() .list() .await @@ -224,15 +222,15 @@ mod tests { .public_key("pubkey".to_string()) .instance_id(inserted_instance.id) .build(); - let inserted_admin = Person::create(conn, &new_person_3).await.unwrap(); + let inserted_admin = Person::create(pool, &new_person_3).await.unwrap(); // admin resolves the report (after taking appropriate action) - PrivateMessageReport::resolve(conn, pm_report.id, inserted_admin.id) + PrivateMessageReport::resolve(pool, pm_report.id, inserted_admin.id) .await .unwrap(); let reports = PrivateMessageReportQuery::builder() - .conn(conn) + .pool(pool) .unresolved_only(Some(false)) .build() .list() @@ -246,8 +244,6 @@ mod tests { reports[0].resolver.as_ref().unwrap().name ); - Instance::delete(conn, inserted_instance.id) - .await - .unwrap(); + Instance::delete(pool, inserted_instance.id).await.unwrap(); } } diff --git a/crates/db_views/src/private_message_view.rs b/crates/db_views/src/private_message_view.rs index 1f35d1992..76b817a96 100644 --- a/crates/db_views/src/private_message_view.rs +++ b/crates/db_views/src/private_message_view.rs @@ -8,12 +8,13 @@ use diesel::{ JoinOnDsl, QueryDsl, }; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ newtypes::{PersonId, PrivateMessageId}, schema::{person, private_message}, source::{person::Person, private_message::PrivateMessage}, traits::JoinView, - utils::{limit_and_offset, GetConn, RunQueryDsl}, + utils::{get_conn, limit_and_offset, DbPool}, }; use tracing::debug; use typed_builder::TypedBuilder; @@ -21,10 +22,8 @@ use typed_builder::TypedBuilder; type PrivateMessageViewTuple = (PrivateMessage, Person, Person); impl PrivateMessageView { - pub async fn read( - mut conn: impl GetConn, - private_message_id: PrivateMessageId, - ) -> Result { + pub async fn read(pool: &DbPool, private_message_id: PrivateMessageId) -> Result { + let conn = &mut get_conn(pool).await?; let person_alias_1 = diesel::alias!(person as person1); let (private_message, creator, recipient) = private_message::table @@ -50,11 +49,9 @@ impl PrivateMessageView { } /// Gets the number of unread messages - pub async fn get_unread_messages( - mut conn: impl GetConn, - my_person_id: PersonId, - ) -> Result { + pub async fn get_unread_messages(pool: &DbPool, my_person_id: PersonId) -> Result { use diesel::dsl::count; + let conn = &mut get_conn(pool).await?; private_message::table .filter(private_message::read.eq(false)) .filter(private_message::recipient_id.eq(my_person_id)) @@ -67,9 +64,9 @@ impl PrivateMessageView { #[derive(TypedBuilder)] #[builder(field_defaults(default))] -pub struct PrivateMessageQuery { +pub struct PrivateMessageQuery<'a> { #[builder(!default)] - conn: Conn, + pool: &'a DbPool, #[builder(!default)] recipient_id: PersonId, unread_only: Option, @@ -77,9 +74,9 @@ pub struct PrivateMessageQuery { limit: Option, } -impl PrivateMessageQuery { +impl<'a> PrivateMessageQuery<'a> { pub async fn list(self) -> Result, Error> { - let mut conn = self.conn; + let conn = &mut get_conn(self.pool).await?; let person_alias_1 = diesel::alias!(person as person1); let mut query = private_message::table diff --git a/crates/db_views/src/registration_application_view.rs b/crates/db_views/src/registration_application_view.rs index a749fd1c5..9963ed466 100644 --- a/crates/db_views/src/registration_application_view.rs +++ b/crates/db_views/src/registration_application_view.rs @@ -7,6 +7,7 @@ use diesel::{ NullableExpressionMethods, QueryDsl, }; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ schema::{local_user, person, registration_application}, source::{ @@ -15,7 +16,7 @@ use lemmy_db_schema::{ registration_application::RegistrationApplication, }, traits::JoinView, - utils::{limit_and_offset, GetConn, RunQueryDsl}, + utils::{get_conn, limit_and_offset, DbPool}, }; use typed_builder::TypedBuilder; @@ -23,10 +24,8 @@ type RegistrationApplicationViewTuple = (RegistrationApplication, LocalUser, Person, Option); impl RegistrationApplicationView { - pub async fn read( - mut conn: impl GetConn, - registration_application_id: i32, - ) -> Result { + pub async fn read(pool: &DbPool, registration_application_id: i32) -> Result { + let conn = &mut get_conn(pool).await?; let person_alias_1 = diesel::alias!(person as person1); let (registration_application, creator_local_user, creator, admin) = @@ -59,10 +58,8 @@ impl RegistrationApplicationView { } /// Returns the current unread registration_application count - pub async fn get_unread_count( - mut conn: impl GetConn, - verified_email_only: bool, - ) -> Result { + pub async fn get_unread_count(pool: &DbPool, verified_email_only: bool) -> Result { + let conn = &mut get_conn(pool).await?; let person_alias_1 = diesel::alias!(person as person1); let mut query = registration_application::table @@ -88,18 +85,18 @@ impl RegistrationApplicationView { #[derive(TypedBuilder)] #[builder(field_defaults(default))] -pub struct RegistrationApplicationQuery { +pub struct RegistrationApplicationQuery<'a> { #[builder(!default)] - conn: Conn, + pool: &'a DbPool, unread_only: Option, verified_email_only: Option, page: Option, limit: Option, } -impl RegistrationApplicationQuery { +impl<'a> RegistrationApplicationQuery<'a> { pub async fn list(self) -> Result, Error> { - let mut conn = self.conn; + let conn = &mut get_conn(self.pool).await?; let person_alias_1 = diesel::alias!(person as person1); let mut query = registration_application::table @@ -133,9 +130,7 @@ impl RegistrationApplicationQuery { .offset(offset) .order_by(registration_application::published.desc()); - let res = query - .load::(conn) - .await?; + let res = query.load::(conn).await?; Ok( res @@ -176,16 +171,16 @@ mod tests { }, }, traits::Crud, - utils::build_db_conn_for_tests, + utils::build_db_pool_for_tests, }; use serial_test::serial; #[tokio::test] #[serial] async fn test_crud() { - let mut conn = build_db_conn_for_tests().await; + let pool = &build_db_pool_for_tests().await; - let inserted_instance = Instance::read_or_create(conn, "my_domain.tld".to_string()) + let inserted_instance = Instance::read_or_create(pool, "my_domain.tld".to_string()) .await .unwrap(); @@ -196,16 +191,14 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_timmy_person = Person::create(conn, &timmy_person_form) - .await - .unwrap(); + let inserted_timmy_person = Person::create(pool, &timmy_person_form).await.unwrap(); let timmy_local_user_form = LocalUserInsertForm::builder() .person_id(inserted_timmy_person.id) .password_encrypted("nada".to_string()) .build(); - let _inserted_timmy_local_user = LocalUser::create(conn, &timmy_local_user_form) + let _inserted_timmy_local_user = LocalUser::create(pool, &timmy_local_user_form) .await .unwrap(); @@ -215,14 +208,14 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_sara_person = Person::create(conn, &sara_person_form).await.unwrap(); + let inserted_sara_person = Person::create(pool, &sara_person_form).await.unwrap(); let sara_local_user_form = LocalUserInsertForm::builder() .person_id(inserted_sara_person.id) .password_encrypted("nada".to_string()) .build(); - let inserted_sara_local_user = LocalUser::create(conn, &sara_local_user_form) + let inserted_sara_local_user = LocalUser::create(pool, &sara_local_user_form) .await .unwrap(); @@ -232,11 +225,11 @@ mod tests { answer: "LET ME IIIIINN".to_string(), }; - let sara_app = RegistrationApplication::create(conn, &sara_app_form) + let sara_app = RegistrationApplication::create(pool, &sara_app_form) .await .unwrap(); - let read_sara_app_view = RegistrationApplicationView::read(conn, sara_app.id) + let read_sara_app_view = RegistrationApplicationView::read(pool, sara_app.id) .await .unwrap(); @@ -246,14 +239,14 @@ mod tests { .instance_id(inserted_instance.id) .build(); - let inserted_jess_person = Person::create(conn, &jess_person_form).await.unwrap(); + let inserted_jess_person = Person::create(pool, &jess_person_form).await.unwrap(); let jess_local_user_form = LocalUserInsertForm::builder() .person_id(inserted_jess_person.id) .password_encrypted("nada".to_string()) .build(); - let inserted_jess_local_user = LocalUser::create(conn, &jess_local_user_form) + let inserted_jess_local_user = LocalUser::create(pool, &jess_local_user_form) .await .unwrap(); @@ -263,11 +256,11 @@ mod tests { answer: "LET ME IIIIINN".to_string(), }; - let jess_app = RegistrationApplication::create(conn, &jess_app_form) + let jess_app = RegistrationApplication::create(pool, &jess_app_form) .await .unwrap(); - let read_jess_app_view = RegistrationApplicationView::read(conn, jess_app.id) + let read_jess_app_view = RegistrationApplicationView::read(pool, jess_app.id) .await .unwrap(); @@ -327,7 +320,7 @@ mod tests { // Do a batch read of the applications let apps = RegistrationApplicationQuery::builder() - .conn(conn) + .pool(pool) .unread_only(Some(true)) .build() .list() @@ -340,7 +333,7 @@ mod tests { ); // Make sure the counts are correct - let unread_count = RegistrationApplicationView::get_unread_count(conn, false) + let unread_count = RegistrationApplicationView::get_unread_count(pool, false) .await .unwrap(); assert_eq!(unread_count, 2); @@ -351,7 +344,7 @@ mod tests { deny_reason: None, }; - RegistrationApplication::update(conn, sara_app.id, &approve_form) + RegistrationApplication::update(pool, sara_app.id, &approve_form) .await .unwrap(); @@ -360,18 +353,13 @@ mod tests { .accepted_application(Some(true)) .build(); - LocalUser::update( - conn, - inserted_sara_local_user.id, - &approve_local_user_form, - ) - .await - .unwrap(); + LocalUser::update(pool, inserted_sara_local_user.id, &approve_local_user_form) + .await + .unwrap(); - let read_sara_app_view_after_approve = - RegistrationApplicationView::read(conn, sara_app.id) - .await - .unwrap(); + let read_sara_app_view_after_approve = RegistrationApplicationView::read(pool, sara_app.id) + .await + .unwrap(); // Make sure the columns changed expected_sara_app_view @@ -408,7 +396,7 @@ mod tests { // Do a batch read of apps again // It should show only jessicas which is unresolved let apps_after_resolve = RegistrationApplicationQuery::builder() - .conn(conn) + .pool(pool) .unread_only(Some(true)) .build() .list() @@ -417,32 +405,25 @@ mod tests { assert_eq!(apps_after_resolve, vec![read_jess_app_view]); // Make sure the counts are correct - let unread_count_after_approve = - RegistrationApplicationView::get_unread_count(conn, false) - .await - .unwrap(); + let unread_count_after_approve = RegistrationApplicationView::get_unread_count(pool, false) + .await + .unwrap(); assert_eq!(unread_count_after_approve, 1); // Make sure the not undenied_only has all the apps let all_apps = RegistrationApplicationQuery::builder() - .conn(conn) + .pool(pool) .build() .list() .await .unwrap(); assert_eq!(all_apps.len(), 2); - Person::delete(conn, inserted_timmy_person.id) - .await - .unwrap(); - Person::delete(conn, inserted_sara_person.id) - .await - .unwrap(); - Person::delete(conn, inserted_jess_person.id) - .await - .unwrap(); - Instance::delete(conn, inserted_instance.id) + Person::delete(pool, inserted_timmy_person.id) .await .unwrap(); + Person::delete(pool, inserted_sara_person.id).await.unwrap(); + Person::delete(pool, inserted_jess_person.id).await.unwrap(); + Instance::delete(pool, inserted_instance.id).await.unwrap(); } } diff --git a/crates/db_views/src/site_view.rs b/crates/db_views/src/site_view.rs index 2f81f677f..a1d0231a2 100644 --- a/crates/db_views/src/site_view.rs +++ b/crates/db_views/src/site_view.rs @@ -1,14 +1,16 @@ use crate::structs::SiteView; use diesel::{result::Error, ExpressionMethods, JoinOnDsl, QueryDsl}; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ aggregates::structs::SiteAggregates, schema::{local_site, local_site_rate_limit, site, site_aggregates}, source::{local_site::LocalSite, local_site_rate_limit::LocalSiteRateLimit, site::Site}, - utils::{GetConn, RunQueryDsl}, + utils::{get_conn, DbPool}, }; impl SiteView { - pub async fn read_local(mut conn: impl GetConn) -> Result { + pub async fn read_local(pool: &DbPool) -> Result { + let conn = &mut get_conn(pool).await?; let (mut site, local_site, local_site_rate_limit, counts) = site::table .inner_join(local_site::table) .inner_join( diff --git a/crates/db_views_actor/src/comment_reply_view.rs b/crates/db_views_actor/src/comment_reply_view.rs index f8912a88a..42c3a53e0 100644 --- a/crates/db_views_actor/src/comment_reply_view.rs +++ b/crates/db_views_actor/src/comment_reply_view.rs @@ -7,6 +7,7 @@ use diesel::{ NullableExpressionMethods, QueryDsl, }; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ aggregates::structs::CommentAggregates, newtypes::{CommentReplyId, PersonId}, @@ -32,7 +33,7 @@ use lemmy_db_schema::{ post::Post, }, traits::JoinView, - utils::{limit_and_offset, GetConn, RunQueryDsl}, + utils::{get_conn, limit_and_offset, DbPool}, CommentSortType, }; use typed_builder::TypedBuilder; @@ -54,10 +55,11 @@ type CommentReplyViewTuple = ( impl CommentReplyView { pub async fn read( - mut conn: impl GetConn, + pool: &DbPool, comment_reply_id: CommentReplyId, my_person_id: Option, ) -> Result { + let conn = &mut get_conn(pool).await?; let person_alias_1 = diesel::alias!(person as person1); // The left join below will return None in this case @@ -153,12 +155,11 @@ impl CommentReplyView { } /// Gets the number of unread replies - pub async fn get_unread_replies( - mut conn: impl GetConn, - my_person_id: PersonId, - ) -> Result { + pub async fn get_unread_replies(pool: &DbPool, my_person_id: PersonId) -> Result { use diesel::dsl::count; + let conn = &mut get_conn(pool).await?; + comment_reply::table .inner_join(comment::table) .filter(comment_reply::recipient_id.eq(my_person_id)) @@ -173,9 +174,9 @@ impl CommentReplyView { #[derive(TypedBuilder)] #[builder(field_defaults(default))] -pub struct CommentReplyQuery { +pub struct CommentReplyQuery<'a> { #[builder(!default)] - conn: Conn, + pool: &'a DbPool, my_person_id: Option, recipient_id: Option, sort: Option, @@ -185,9 +186,9 @@ pub struct CommentReplyQuery { limit: Option, } -impl CommentReplyQuery { +impl<'a> CommentReplyQuery<'a> { pub async fn list(self) -> Result, Error> { - let mut conn = self.conn; + let conn = &mut get_conn(self.pool).await?; let person_alias_1 = diesel::alias!(person as person1); diff --git a/crates/db_views_actor/src/community_block_view.rs b/crates/db_views_actor/src/community_block_view.rs index b7e14edba..d87bea37f 100644 --- a/crates/db_views_actor/src/community_block_view.rs +++ b/crates/db_views_actor/src/community_block_view.rs @@ -1,17 +1,19 @@ use crate::structs::CommunityBlockView; use diesel::{result::Error, ExpressionMethods, QueryDsl}; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ newtypes::PersonId, schema::{community, community_block, person}, source::{community::Community, person::Person}, traits::JoinView, - utils::{GetConn, RunQueryDsl}, + utils::{get_conn, DbPool}, }; type CommunityBlockViewTuple = (Person, Community); impl CommunityBlockView { - pub async fn for_person(mut conn: impl GetConn, person_id: PersonId) -> Result, Error> { + pub async fn for_person(pool: &DbPool, person_id: PersonId) -> Result, Error> { + let conn = &mut get_conn(pool).await?; let res = community_block::table .inner_join(person::table) .inner_join(community::table) diff --git a/crates/db_views_actor/src/community_follower_view.rs b/crates/db_views_actor/src/community_follower_view.rs index fcda6461a..ccc7ae706 100644 --- a/crates/db_views_actor/src/community_follower_view.rs +++ b/crates/db_views_actor/src/community_follower_view.rs @@ -1,20 +1,19 @@ use crate::structs::CommunityFollowerView; use diesel::{result::Error, ExpressionMethods, QueryDsl}; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ newtypes::{CommunityId, PersonId}, schema::{community, community_follower, person}, source::{community::Community, person::Person}, traits::JoinView, - utils::{GetConn, RunQueryDsl}, + utils::{get_conn, DbPool}, }; type CommunityFollowerViewTuple = (Community, Person); impl CommunityFollowerView { - pub async fn for_community( - mut conn: impl GetConn, - community_id: CommunityId, - ) -> Result, Error> { + pub async fn for_community(pool: &DbPool, community_id: CommunityId) -> Result, Error> { + let conn = &mut get_conn(pool).await?; let res = community_follower::table .inner_join(community::table) .inner_join(person::table) @@ -27,7 +26,8 @@ impl CommunityFollowerView { Ok(res.into_iter().map(Self::from_tuple).collect()) } - pub async fn for_person(mut conn: impl GetConn, person_id: PersonId) -> Result, Error> { + pub async fn for_person(pool: &DbPool, person_id: PersonId) -> Result, Error> { + let conn = &mut get_conn(pool).await?; let res = community_follower::table .inner_join(community::table) .inner_join(person::table) diff --git a/crates/db_views_actor/src/community_moderator_view.rs b/crates/db_views_actor/src/community_moderator_view.rs index 180626cc3..afdfbfb28 100644 --- a/crates/db_views_actor/src/community_moderator_view.rs +++ b/crates/db_views_actor/src/community_moderator_view.rs @@ -1,20 +1,19 @@ use crate::structs::CommunityModeratorView; use diesel::{result::Error, ExpressionMethods, QueryDsl}; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ newtypes::{CommunityId, PersonId}, schema::{community, community_moderator, person}, source::{community::Community, person::Person}, traits::JoinView, - utils::{GetConn, RunQueryDsl}, + utils::{get_conn, DbPool}, }; type CommunityModeratorViewTuple = (Community, Person); impl CommunityModeratorView { - pub async fn for_community( - mut conn: impl GetConn, - community_id: CommunityId, - ) -> Result, Error> { + pub async fn for_community(pool: &DbPool, community_id: CommunityId) -> Result, Error> { + let conn = &mut get_conn(pool).await?; let res = community_moderator::table .inner_join(community::table) .inner_join(person::table) @@ -26,7 +25,8 @@ impl CommunityModeratorView { Ok(res.into_iter().map(Self::from_tuple).collect()) } - pub async fn for_person(mut conn: impl GetConn, person_id: PersonId) -> Result, Error> { + pub async fn for_person(pool: &DbPool, person_id: PersonId) -> Result, Error> { + let conn = &mut get_conn(pool).await?; let res = community_moderator::table .inner_join(community::table) .inner_join(person::table) @@ -42,7 +42,8 @@ impl CommunityModeratorView { /// Finds all communities first mods / creators /// Ideally this should be a group by, but diesel doesn't support it yet - pub async fn get_community_first_mods(mut conn: impl GetConn) -> Result, Error> { + pub async fn get_community_first_mods(pool: &DbPool) -> Result, Error> { + let conn = &mut get_conn(pool).await?; let res = community_moderator::table .inner_join(community::table) .inner_join(person::table) diff --git a/crates/db_views_actor/src/community_person_ban_view.rs b/crates/db_views_actor/src/community_person_ban_view.rs index d6616b4db..35eacf0f7 100644 --- a/crates/db_views_actor/src/community_person_ban_view.rs +++ b/crates/db_views_actor/src/community_person_ban_view.rs @@ -1,18 +1,20 @@ use crate::structs::CommunityPersonBanView; use diesel::{result::Error, ExpressionMethods, QueryDsl}; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ newtypes::{CommunityId, PersonId}, schema::{community, community_person_ban, person}, source::{community::Community, person::Person}, - utils::{GetConn, RunQueryDsl}, + utils::{get_conn, DbPool}, }; impl CommunityPersonBanView { pub async fn get( - mut conn: impl GetConn, + pool: &DbPool, from_person_id: PersonId, from_community_id: CommunityId, ) -> Result { + let conn = &mut get_conn(pool).await?; let (community, person) = community_person_ban::table .inner_join(community::table) .inner_join(person::table) diff --git a/crates/db_views_actor/src/community_view.rs b/crates/db_views_actor/src/community_view.rs index f965485ad..94bcdaf92 100644 --- a/crates/db_views_actor/src/community_view.rs +++ b/crates/db_views_actor/src/community_view.rs @@ -8,6 +8,7 @@ use diesel::{ PgTextExpressionMethods, QueryDsl, }; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ aggregates::structs::CommunityAggregates, newtypes::{CommunityId, PersonId}, @@ -18,7 +19,7 @@ use lemmy_db_schema::{ local_user::LocalUser, }, traits::JoinView, - utils::{fuzzy_search, limit_and_offset, GetConn, RunQueryDsl}, + utils::{fuzzy_search, get_conn, limit_and_offset, DbPool}, ListingType, SortType, }; @@ -33,11 +34,12 @@ type CommunityViewTuple = ( impl CommunityView { pub async fn read( - mut conn: impl GetConn, + pool: &DbPool, community_id: CommunityId, my_person_id: Option, is_mod_or_admin: Option, ) -> Result { + let conn = &mut get_conn(pool).await?; // The left join below will return None in this case let person_id_join = my_person_id.unwrap_or(PersonId(-1)); @@ -73,8 +75,7 @@ impl CommunityView { .filter(community::deleted.eq(false)); } - let (community, counts, follower, blocked) = - query.first::(conn).await?; + let (community, counts, follower, blocked) = query.first::(conn).await?; Ok(CommunityView { community, @@ -85,11 +86,11 @@ impl CommunityView { } pub async fn is_mod_or_admin( - mut conn: impl GetConn, + pool: &DbPool, person_id: PersonId, community_id: CommunityId, ) -> Result { - let is_mod = CommunityModeratorView::for_community(conn, community_id) + let is_mod = CommunityModeratorView::for_community(pool, community_id) .await .map(|v| { v.into_iter() @@ -102,7 +103,7 @@ impl CommunityView { return Ok(true); } - let is_admin = PersonView::admins(conn) + let is_admin = PersonView::admins(pool) .await .map(|v| { v.into_iter() @@ -117,9 +118,9 @@ impl CommunityView { #[derive(TypedBuilder)] #[builder(field_defaults(default))] -pub struct CommunityQuery<'a, Conn> { +pub struct CommunityQuery<'a> { #[builder(!default)] - conn: Conn, + pool: &'a DbPool, listing_type: Option, sort: Option, local_user: Option<&'a LocalUser>, @@ -130,11 +131,11 @@ pub struct CommunityQuery<'a, Conn> { limit: Option, } -impl<'a, Conn: GetConn> CommunityQuery<'a, Conn> { +impl<'a> CommunityQuery<'a> { pub async fn list(self) -> Result, Error> { use SortType::*; - let mut conn = self.conn; + let conn = &mut get_conn(self.pool).await?; // The left join below will return None in this case let person_id_join = self.local_user.map(|l| l.person_id).unwrap_or(PersonId(-1)); diff --git a/crates/db_views_actor/src/person_block_view.rs b/crates/db_views_actor/src/person_block_view.rs index 85fd81e6f..6e10ee7b6 100644 --- a/crates/db_views_actor/src/person_block_view.rs +++ b/crates/db_views_actor/src/person_block_view.rs @@ -1,17 +1,19 @@ use crate::structs::PersonBlockView; use diesel::{result::Error, ExpressionMethods, JoinOnDsl, QueryDsl}; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ newtypes::PersonId, schema::{person, person_block}, source::person::Person, traits::JoinView, - utils::{GetConn, RunQueryDsl}, + utils::{get_conn, DbPool}, }; type PersonBlockViewTuple = (Person, Person); impl PersonBlockView { - pub async fn for_person(mut conn: impl GetConn, person_id: PersonId) -> Result, Error> { + pub async fn for_person(pool: &DbPool, person_id: PersonId) -> Result, Error> { + let conn = &mut get_conn(pool).await?; let target_person_alias = diesel::alias!(person as person1); let res = person_block::table diff --git a/crates/db_views_actor/src/person_mention_view.rs b/crates/db_views_actor/src/person_mention_view.rs index c63aec932..803abdb39 100644 --- a/crates/db_views_actor/src/person_mention_view.rs +++ b/crates/db_views_actor/src/person_mention_view.rs @@ -8,6 +8,7 @@ use diesel::{ NullableExpressionMethods, QueryDsl, }; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ aggregates::structs::CommentAggregates, newtypes::{PersonId, PersonMentionId}, @@ -33,7 +34,7 @@ use lemmy_db_schema::{ post::Post, }, traits::JoinView, - utils::{limit_and_offset, GetConn, RunQueryDsl}, + utils::{get_conn, limit_and_offset, DbPool}, CommentSortType, }; use typed_builder::TypedBuilder; @@ -55,10 +56,11 @@ type PersonMentionViewTuple = ( impl PersonMentionView { pub async fn read( - mut conn: impl GetConn, + pool: &DbPool, person_mention_id: PersonMentionId, my_person_id: Option, ) -> Result { + let conn = &mut get_conn(pool).await?; let person_alias_1 = diesel::alias!(person as person1); // The left join below will return None in this case @@ -154,11 +156,9 @@ impl PersonMentionView { } /// Gets the number of unread mentions - pub async fn get_unread_mentions( - mut conn: impl GetConn, - my_person_id: PersonId, - ) -> Result { + pub async fn get_unread_mentions(pool: &DbPool, my_person_id: PersonId) -> Result { use diesel::dsl::count; + let conn = &mut get_conn(pool).await?; person_mention::table .inner_join(comment::table) @@ -174,9 +174,9 @@ impl PersonMentionView { #[derive(TypedBuilder)] #[builder(field_defaults(default))] -pub struct PersonMentionQuery { +pub struct PersonMentionQuery<'a> { #[builder(!default)] - conn: Conn, + pool: &'a DbPool, my_person_id: Option, recipient_id: Option, sort: Option, @@ -186,9 +186,9 @@ pub struct PersonMentionQuery { limit: Option, } -impl PersonMentionQuery { +impl<'a> PersonMentionQuery<'a> { pub async fn list(self) -> Result, Error> { - let mut conn = self.conn; + let conn = &mut get_conn(self.pool).await?; let person_alias_1 = diesel::alias!(person as person1); diff --git a/crates/db_views_actor/src/person_view.rs b/crates/db_views_actor/src/person_view.rs index cf13b96fb..2a7a2ce79 100644 --- a/crates/db_views_actor/src/person_view.rs +++ b/crates/db_views_actor/src/person_view.rs @@ -7,13 +7,14 @@ use diesel::{ PgTextExpressionMethods, QueryDsl, }; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ aggregates::structs::PersonAggregates, newtypes::PersonId, schema::{person, person_aggregates}, source::person::Person, traits::JoinView, - utils::{fuzzy_search, limit_and_offset, GetConn, RunQueryDsl}, + utils::{fuzzy_search, get_conn, limit_and_offset, DbPool}, SortType, }; use std::iter::Iterator; @@ -22,7 +23,8 @@ use typed_builder::TypedBuilder; type PersonViewTuple = (Person, PersonAggregates); impl PersonView { - pub async fn read(mut conn: impl GetConn, person_id: PersonId) -> Result { + pub async fn read(pool: &DbPool, person_id: PersonId) -> Result { + let conn = &mut get_conn(pool).await?; let res = person::table .find(person_id) .inner_join(person_aggregates::table) @@ -32,7 +34,8 @@ impl PersonView { Ok(Self::from_tuple(res)) } - pub async fn admins(mut conn: impl GetConn) -> Result, Error> { + pub async fn admins(pool: &DbPool) -> Result, Error> { + let conn = &mut get_conn(pool).await?; let admins = person::table .inner_join(person_aggregates::table) .select((person::all_columns, person_aggregates::all_columns)) @@ -45,7 +48,8 @@ impl PersonView { Ok(admins.into_iter().map(Self::from_tuple).collect()) } - pub async fn banned(mut conn: impl GetConn) -> Result, Error> { + pub async fn banned(pool: &DbPool) -> Result, Error> { + let conn = &mut get_conn(pool).await?; let banned = person::table .inner_join(person_aggregates::table) .select((person::all_columns, person_aggregates::all_columns)) @@ -66,18 +70,18 @@ impl PersonView { #[derive(TypedBuilder)] #[builder(field_defaults(default))] -pub struct PersonQuery { +pub struct PersonQuery<'a> { #[builder(!default)] - conn: Conn, + pool: &'a DbPool, sort: Option, search_term: Option, page: Option, limit: Option, } -impl PersonQuery { +impl<'a> PersonQuery<'a> { pub async fn list(self) -> Result, Error> { - let mut conn = self.conn; + let conn = &mut get_conn(self.pool).await?; let mut query = person::table .inner_join(person_aggregates::table) .select((person::all_columns, person_aggregates::all_columns)) diff --git a/crates/db_views_moderator/src/admin_purge_comment_view.rs b/crates/db_views_moderator/src/admin_purge_comment_view.rs index 52b0c0bdd..12e47fbbc 100644 --- a/crates/db_views_moderator/src/admin_purge_comment_view.rs +++ b/crates/db_views_moderator/src/admin_purge_comment_view.rs @@ -8,18 +8,20 @@ use diesel::{ NullableExpressionMethods, QueryDsl, }; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ newtypes::PersonId, schema::{admin_purge_comment, person, post}, source::{moderator::AdminPurgeComment, person::Person, post::Post}, traits::JoinView, - utils::{limit_and_offset, GetConn, RunQueryDsl}, + utils::{get_conn, limit_and_offset, DbPool}, }; type AdminPurgeCommentViewTuple = (AdminPurgeComment, Option, Post); impl AdminPurgeCommentView { - pub async fn list(mut conn: impl GetConn, params: ModlogListParams) -> Result, Error> { + pub async fn list(pool: &DbPool, params: ModlogListParams) -> Result, Error> { + let conn = &mut get_conn(pool).await?; let admin_person_id_join = params.mod_person_id.unwrap_or(PersonId(-1)); let show_mod_names = !params.hide_modlog_names; let show_mod_names_expr = show_mod_names.as_sql::(); diff --git a/crates/db_views_moderator/src/admin_purge_community_view.rs b/crates/db_views_moderator/src/admin_purge_community_view.rs index 9cc51b87c..e3a7a7897 100644 --- a/crates/db_views_moderator/src/admin_purge_community_view.rs +++ b/crates/db_views_moderator/src/admin_purge_community_view.rs @@ -8,18 +8,20 @@ use diesel::{ NullableExpressionMethods, QueryDsl, }; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ newtypes::PersonId, schema::{admin_purge_community, person}, source::{moderator::AdminPurgeCommunity, person::Person}, traits::JoinView, - utils::{limit_and_offset, GetConn, RunQueryDsl}, + utils::{get_conn, limit_and_offset, DbPool}, }; type AdminPurgeCommunityViewTuple = (AdminPurgeCommunity, Option); impl AdminPurgeCommunityView { - pub async fn list(mut conn: impl GetConn, params: ModlogListParams) -> Result, Error> { + pub async fn list(pool: &DbPool, params: ModlogListParams) -> Result, Error> { + let conn = &mut get_conn(pool).await?; let admin_person_id_join = params.mod_person_id.unwrap_or(PersonId(-1)); let show_mod_names = !params.hide_modlog_names; let show_mod_names_expr = show_mod_names.as_sql::(); diff --git a/crates/db_views_moderator/src/admin_purge_person_view.rs b/crates/db_views_moderator/src/admin_purge_person_view.rs index 25d5735df..fff5b2d51 100644 --- a/crates/db_views_moderator/src/admin_purge_person_view.rs +++ b/crates/db_views_moderator/src/admin_purge_person_view.rs @@ -8,18 +8,21 @@ use diesel::{ NullableExpressionMethods, QueryDsl, }; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ newtypes::PersonId, schema::{admin_purge_person, person}, source::{moderator::AdminPurgePerson, person::Person}, traits::JoinView, - utils::{limit_and_offset, GetConn, RunQueryDsl}, + utils::{get_conn, limit_and_offset, DbPool}, }; type AdminPurgePersonViewTuple = (AdminPurgePerson, Option); impl AdminPurgePersonView { - pub async fn list(mut conn: impl GetConn, params: ModlogListParams) -> Result, Error> { + pub async fn list(pool: &DbPool, params: ModlogListParams) -> Result, Error> { + let conn = &mut get_conn(pool).await?; + let admin_person_id_join = params.mod_person_id.unwrap_or(PersonId(-1)); let show_mod_names = !params.hide_modlog_names; let show_mod_names_expr = show_mod_names.as_sql::(); diff --git a/crates/db_views_moderator/src/admin_purge_post_view.rs b/crates/db_views_moderator/src/admin_purge_post_view.rs index d01faf1ab..e37e66b1b 100644 --- a/crates/db_views_moderator/src/admin_purge_post_view.rs +++ b/crates/db_views_moderator/src/admin_purge_post_view.rs @@ -8,18 +8,21 @@ use diesel::{ NullableExpressionMethods, QueryDsl, }; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ newtypes::PersonId, schema::{admin_purge_post, community, person}, source::{community::Community, moderator::AdminPurgePost, person::Person}, traits::JoinView, - utils::{limit_and_offset, GetConn, RunQueryDsl}, + utils::{get_conn, limit_and_offset, DbPool}, }; type AdminPurgePostViewTuple = (AdminPurgePost, Option, Community); impl AdminPurgePostView { - pub async fn list(mut conn: impl GetConn, params: ModlogListParams) -> Result, Error> { + pub async fn list(pool: &DbPool, params: ModlogListParams) -> Result, Error> { + let conn = &mut get_conn(pool).await?; + let admin_person_id_join = params.mod_person_id.unwrap_or(PersonId(-1)); let show_mod_names = !params.hide_modlog_names; let show_mod_names_expr = show_mod_names.as_sql::(); diff --git a/crates/db_views_moderator/src/mod_add_community_view.rs b/crates/db_views_moderator/src/mod_add_community_view.rs index 2067cc896..6df6376f5 100644 --- a/crates/db_views_moderator/src/mod_add_community_view.rs +++ b/crates/db_views_moderator/src/mod_add_community_view.rs @@ -8,18 +8,20 @@ use diesel::{ NullableExpressionMethods, QueryDsl, }; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ newtypes::PersonId, schema::{community, mod_add_community, person}, source::{community::Community, moderator::ModAddCommunity, person::Person}, traits::JoinView, - utils::{limit_and_offset, GetConn, RunQueryDsl}, + utils::{get_conn, limit_and_offset, DbPool}, }; type ModAddCommunityViewTuple = (ModAddCommunity, Option, Community, Person); impl ModAddCommunityView { - pub async fn list(mut conn: impl GetConn, params: ModlogListParams) -> Result, Error> { + pub async fn list(pool: &DbPool, params: ModlogListParams) -> Result, Error> { + let conn = &mut get_conn(pool).await?; let person_alias_1 = diesel::alias!(person as person1); let admin_person_id_join = params.mod_person_id.unwrap_or(PersonId(-1)); let show_mod_names = !params.hide_modlog_names; diff --git a/crates/db_views_moderator/src/mod_add_view.rs b/crates/db_views_moderator/src/mod_add_view.rs index b031c08b7..ef408ce3a 100644 --- a/crates/db_views_moderator/src/mod_add_view.rs +++ b/crates/db_views_moderator/src/mod_add_view.rs @@ -8,18 +8,20 @@ use diesel::{ NullableExpressionMethods, QueryDsl, }; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ newtypes::PersonId, schema::{mod_add, person}, source::{moderator::ModAdd, person::Person}, traits::JoinView, - utils::{limit_and_offset, GetConn, RunQueryDsl}, + utils::{get_conn, limit_and_offset, DbPool}, }; type ModAddViewTuple = (ModAdd, Option, Person); impl ModAddView { - pub async fn list(mut conn: impl GetConn, params: ModlogListParams) -> Result, Error> { + pub async fn list(pool: &DbPool, params: ModlogListParams) -> Result, Error> { + let conn = &mut get_conn(pool).await?; let person_alias_1 = diesel::alias!(person as person1); let admin_person_id_join = params.mod_person_id.unwrap_or(PersonId(-1)); let show_mod_names = !params.hide_modlog_names; diff --git a/crates/db_views_moderator/src/mod_ban_from_community_view.rs b/crates/db_views_moderator/src/mod_ban_from_community_view.rs index e75d957ef..c7fb73956 100644 --- a/crates/db_views_moderator/src/mod_ban_from_community_view.rs +++ b/crates/db_views_moderator/src/mod_ban_from_community_view.rs @@ -8,18 +8,21 @@ use diesel::{ NullableExpressionMethods, QueryDsl, }; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ newtypes::PersonId, schema::{community, mod_ban_from_community, person}, source::{community::Community, moderator::ModBanFromCommunity, person::Person}, traits::JoinView, - utils::{limit_and_offset, GetConn, RunQueryDsl}, + utils::{get_conn, limit_and_offset, DbPool}, }; type ModBanFromCommunityViewTuple = (ModBanFromCommunity, Option, Community, Person); impl ModBanFromCommunityView { - pub async fn list(mut conn: impl GetConn, params: ModlogListParams) -> Result, Error> { + pub async fn list(pool: &DbPool, params: ModlogListParams) -> Result, Error> { + let conn = &mut get_conn(pool).await?; + let person_alias_1 = diesel::alias!(person as person1); let admin_person_id_join = params.mod_person_id.unwrap_or(PersonId(-1)); let show_mod_names = !params.hide_modlog_names; diff --git a/crates/db_views_moderator/src/mod_ban_view.rs b/crates/db_views_moderator/src/mod_ban_view.rs index 274c5f57d..7bdf0dcf7 100644 --- a/crates/db_views_moderator/src/mod_ban_view.rs +++ b/crates/db_views_moderator/src/mod_ban_view.rs @@ -8,18 +8,20 @@ use diesel::{ NullableExpressionMethods, QueryDsl, }; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ newtypes::PersonId, schema::{mod_ban, person}, source::{moderator::ModBan, person::Person}, traits::JoinView, - utils::{limit_and_offset, GetConn, RunQueryDsl}, + utils::{get_conn, limit_and_offset, DbPool}, }; type ModBanViewTuple = (ModBan, Option, Person); impl ModBanView { - pub async fn list(mut conn: impl GetConn, params: ModlogListParams) -> Result, Error> { + pub async fn list(pool: &DbPool, params: ModlogListParams) -> Result, Error> { + let conn = &mut get_conn(pool).await?; let person_alias_1 = diesel::alias!(person as person1); let admin_person_id_join = params.mod_person_id.unwrap_or(PersonId(-1)); let show_mod_names = !params.hide_modlog_names; diff --git a/crates/db_views_moderator/src/mod_feature_post_view.rs b/crates/db_views_moderator/src/mod_feature_post_view.rs index 4d8b23060..66bd4264f 100644 --- a/crates/db_views_moderator/src/mod_feature_post_view.rs +++ b/crates/db_views_moderator/src/mod_feature_post_view.rs @@ -8,18 +8,20 @@ use diesel::{ NullableExpressionMethods, QueryDsl, }; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ newtypes::PersonId, schema::{community, mod_feature_post, person, post}, source::{community::Community, moderator::ModFeaturePost, person::Person, post::Post}, traits::JoinView, - utils::{limit_and_offset, GetConn, RunQueryDsl}, + utils::{get_conn, limit_and_offset, DbPool}, }; type ModFeaturePostViewTuple = (ModFeaturePost, Option, Post, Community); impl ModFeaturePostView { - pub async fn list(mut conn: impl GetConn, params: ModlogListParams) -> Result, Error> { + pub async fn list(pool: &DbPool, params: ModlogListParams) -> Result, Error> { + let conn = &mut get_conn(pool).await?; let person_alias_1 = diesel::alias!(person as person1); let admin_person_id_join = params.mod_person_id.unwrap_or(PersonId(-1)); let show_mod_names = !params.hide_modlog_names; diff --git a/crates/db_views_moderator/src/mod_hide_community_view.rs b/crates/db_views_moderator/src/mod_hide_community_view.rs index ec93b34a6..c2c6294bf 100644 --- a/crates/db_views_moderator/src/mod_hide_community_view.rs +++ b/crates/db_views_moderator/src/mod_hide_community_view.rs @@ -8,19 +8,22 @@ use diesel::{ NullableExpressionMethods, QueryDsl, }; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ newtypes::PersonId, schema::{community, mod_hide_community, person}, source::{community::Community, moderator::ModHideCommunity, person::Person}, traits::JoinView, - utils::{limit_and_offset, GetConn, RunQueryDsl}, + utils::{get_conn, limit_and_offset, DbPool}, }; type ModHideCommunityViewTuple = (ModHideCommunity, Option, Community); impl ModHideCommunityView { // Pass in mod_id as admin_id because only admins can do this action - pub async fn list(mut conn: impl GetConn, params: ModlogListParams) -> Result, Error> { + pub async fn list(pool: &DbPool, params: ModlogListParams) -> Result, Error> { + let conn = &mut get_conn(pool).await?; + let admin_person_id_join = params.mod_person_id.unwrap_or(PersonId(-1)); let show_mod_names = !params.hide_modlog_names; let show_mod_names_expr = show_mod_names.as_sql::(); diff --git a/crates/db_views_moderator/src/mod_lock_post_view.rs b/crates/db_views_moderator/src/mod_lock_post_view.rs index 6a8fe6c5c..15ff7855c 100644 --- a/crates/db_views_moderator/src/mod_lock_post_view.rs +++ b/crates/db_views_moderator/src/mod_lock_post_view.rs @@ -8,18 +8,21 @@ use diesel::{ NullableExpressionMethods, QueryDsl, }; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ newtypes::PersonId, schema::{community, mod_lock_post, person, post}, source::{community::Community, moderator::ModLockPost, person::Person, post::Post}, traits::JoinView, - utils::{limit_and_offset, GetConn, RunQueryDsl}, + utils::{get_conn, limit_and_offset, DbPool}, }; type ModLockPostViewTuple = (ModLockPost, Option, Post, Community); impl ModLockPostView { - pub async fn list(mut conn: impl GetConn, params: ModlogListParams) -> Result, Error> { + pub async fn list(pool: &DbPool, params: ModlogListParams) -> Result, Error> { + let conn = &mut get_conn(pool).await?; + let person_alias_1 = diesel::alias!(person as person1); let admin_person_id_join = params.mod_person_id.unwrap_or(PersonId(-1)); let show_mod_names = !params.hide_modlog_names; diff --git a/crates/db_views_moderator/src/mod_remove_comment_view.rs b/crates/db_views_moderator/src/mod_remove_comment_view.rs index b62510dfc..0d33974b8 100644 --- a/crates/db_views_moderator/src/mod_remove_comment_view.rs +++ b/crates/db_views_moderator/src/mod_remove_comment_view.rs @@ -8,6 +8,7 @@ use diesel::{ NullableExpressionMethods, QueryDsl, }; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ newtypes::PersonId, schema::{comment, community, mod_remove_comment, person, post}, @@ -19,7 +20,7 @@ use lemmy_db_schema::{ post::Post, }, traits::JoinView, - utils::{limit_and_offset, GetConn, RunQueryDsl}, + utils::{get_conn, limit_and_offset, DbPool}, }; type ModRemoveCommentViewTuple = ( @@ -32,7 +33,8 @@ type ModRemoveCommentViewTuple = ( ); impl ModRemoveCommentView { - pub async fn list(mut conn: impl GetConn, params: ModlogListParams) -> Result, Error> { + pub async fn list(pool: &DbPool, params: ModlogListParams) -> Result, Error> { + let conn = &mut get_conn(pool).await?; let person_alias_1 = diesel::alias!(lemmy_db_schema::schema::person as person1); let admin_person_id_join = params.mod_person_id.unwrap_or(PersonId(-1)); let show_mod_names = !params.hide_modlog_names; diff --git a/crates/db_views_moderator/src/mod_remove_community_view.rs b/crates/db_views_moderator/src/mod_remove_community_view.rs index aa90f24be..50f99e528 100644 --- a/crates/db_views_moderator/src/mod_remove_community_view.rs +++ b/crates/db_views_moderator/src/mod_remove_community_view.rs @@ -8,18 +8,20 @@ use diesel::{ NullableExpressionMethods, QueryDsl, }; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ newtypes::PersonId, schema::{community, mod_remove_community, person}, source::{community::Community, moderator::ModRemoveCommunity, person::Person}, traits::JoinView, - utils::{limit_and_offset, GetConn, RunQueryDsl}, + utils::{get_conn, limit_and_offset, DbPool}, }; type ModRemoveCommunityTuple = (ModRemoveCommunity, Option, Community); impl ModRemoveCommunityView { - pub async fn list(mut conn: impl GetConn, params: ModlogListParams) -> Result, Error> { + pub async fn list(pool: &DbPool, params: ModlogListParams) -> Result, Error> { + let conn = &mut get_conn(pool).await?; let admin_person_id_join = params.mod_person_id.unwrap_or(PersonId(-1)); let show_mod_names = !params.hide_modlog_names; let show_mod_names_expr = show_mod_names.as_sql::(); diff --git a/crates/db_views_moderator/src/mod_remove_post_view.rs b/crates/db_views_moderator/src/mod_remove_post_view.rs index 5939fa05f..fff5df466 100644 --- a/crates/db_views_moderator/src/mod_remove_post_view.rs +++ b/crates/db_views_moderator/src/mod_remove_post_view.rs @@ -8,18 +8,21 @@ use diesel::{ NullableExpressionMethods, QueryDsl, }; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ newtypes::PersonId, schema::{community, mod_remove_post, person, post}, source::{community::Community, moderator::ModRemovePost, person::Person, post::Post}, traits::JoinView, - utils::{limit_and_offset, GetConn, RunQueryDsl}, + utils::{get_conn, limit_and_offset, DbPool}, }; type ModRemovePostViewTuple = (ModRemovePost, Option, Post, Community); impl ModRemovePostView { - pub async fn list(mut conn: impl GetConn, params: ModlogListParams) -> Result, Error> { + pub async fn list(pool: &DbPool, params: ModlogListParams) -> Result, Error> { + let conn = &mut get_conn(pool).await?; + let person_alias_1 = diesel::alias!(person as person1); let admin_person_id_join = params.mod_person_id.unwrap_or(PersonId(-1)); let show_mod_names = !params.hide_modlog_names; diff --git a/crates/db_views_moderator/src/mod_transfer_community_view.rs b/crates/db_views_moderator/src/mod_transfer_community_view.rs index c7c5afbd2..60da8e83f 100644 --- a/crates/db_views_moderator/src/mod_transfer_community_view.rs +++ b/crates/db_views_moderator/src/mod_transfer_community_view.rs @@ -8,18 +8,21 @@ use diesel::{ NullableExpressionMethods, QueryDsl, }; +use diesel_async::RunQueryDsl; use lemmy_db_schema::{ newtypes::PersonId, schema::{community, mod_transfer_community, person}, source::{community::Community, moderator::ModTransferCommunity, person::Person}, traits::JoinView, - utils::{limit_and_offset, GetConn, RunQueryDsl}, + utils::{get_conn, limit_and_offset, DbPool}, }; type ModTransferCommunityViewTuple = (ModTransferCommunity, Option, Community, Person); impl ModTransferCommunityView { - pub async fn list(mut conn: impl GetConn, params: ModlogListParams) -> Result, Error> { + pub async fn list(pool: &DbPool, params: ModlogListParams) -> Result, Error> { + let conn = &mut get_conn(pool).await?; + let person_alias_1 = diesel::alias!(person as person1); let admin_person_id_join = params.mod_person_id.unwrap_or(PersonId(-1)); let show_mod_names = !params.hide_modlog_names; diff --git a/crates/routes/src/feeds.rs b/crates/routes/src/feeds.rs index 79f9423d0..2d894c683 100644 --- a/crates/routes/src/feeds.rs +++ b/crates/routes/src/feeds.rs @@ -6,7 +6,7 @@ use lemmy_db_schema::{ newtypes::LocalUserId, source::{community::Community, local_user::LocalUser, person::Person}, traits::{ApubActor, Crud}, - utils::{get_conn, DbPool}, + utils::DbPool, CommentSortType, ListingType, SortType, @@ -122,10 +122,10 @@ async fn get_feed_data( limit: i64, page: i64, ) -> Result { - let site_view = SiteView::read_local(context.conn().await?).await?; + let site_view = SiteView::read_local(context.pool()).await?; let posts = PostQuery::builder() - .conn(context.conn().await?) + .pool(context.pool()) .listing_type(Some(listing_type)) .sort(Some(sort_type)) .limit(Some(limit)) @@ -234,11 +234,11 @@ async fn get_feed_user( user_name: &str, protocol_and_hostname: &str, ) -> Result { - let site_view = SiteView::read_local(get_conn(pool).await?).await?; - let person = Person::read_from_name(get_conn(pool).await?, user_name, false).await?; + let site_view = SiteView::read_local(pool).await?; + let person = Person::read_from_name(pool, user_name, false).await?; let posts = PostQuery::builder() - .conn(get_conn(pool).await?) + .pool(pool) .listing_type(Some(ListingType::All)) .sort(Some(*sort_type)) .creator_id(Some(person.id)) @@ -269,11 +269,11 @@ async fn get_feed_community( community_name: &str, protocol_and_hostname: &str, ) -> Result { - let site_view = SiteView::read_local(get_conn(pool).await?).await?; - let community = Community::read_from_name(get_conn(pool).await?, community_name, false).await?; + let site_view = SiteView::read_local(pool).await?; + let community = Community::read_from_name(pool, community_name, false).await?; let posts = PostQuery::builder() - .conn(get_conn(pool).await?) + .pool(pool) .sort(Some(*sort_type)) .community_id(Some(community.id)) .limit(Some(*limit)) @@ -308,12 +308,12 @@ async fn get_feed_front( jwt: &str, protocol_and_hostname: &str, ) -> Result { - let site_view = SiteView::read_local(get_conn(pool).await?).await?; + let site_view = SiteView::read_local(pool).await?; let local_user_id = LocalUserId(Claims::decode(jwt, jwt_secret)?.claims.sub); - let local_user = LocalUser::read(get_conn(pool).await?, local_user_id).await?; + let local_user = LocalUser::read(pool, local_user_id).await?; let posts = PostQuery::builder() - .conn(get_conn(pool).await?) + .pool(pool) .listing_type(Some(ListingType::Subscribed)) .local_user(Some(&local_user)) .sort(Some(*sort_type)) @@ -346,16 +346,16 @@ async fn get_feed_inbox( jwt: &str, protocol_and_hostname: &str, ) -> Result { - let site_view = SiteView::read_local(get_conn(pool).await?).await?; + let site_view = SiteView::read_local(pool).await?; let local_user_id = LocalUserId(Claims::decode(jwt, jwt_secret)?.claims.sub); - let local_user = LocalUser::read(get_conn(pool).await?, local_user_id).await?; + let local_user = LocalUser::read(pool, local_user_id).await?; let person_id = local_user.person_id; let show_bot_accounts = local_user.show_bot_accounts; let sort = CommentSortType::New; let replies = CommentReplyQuery::builder() - .conn(get_conn(pool).await?) + .pool(pool) .recipient_id(Some(person_id)) .my_person_id(Some(person_id)) .show_bot_accounts(Some(show_bot_accounts)) @@ -366,7 +366,7 @@ async fn get_feed_inbox( .await?; let mentions = PersonMentionQuery::builder() - .conn(get_conn(pool).await?) + .pool(pool) .recipient_id(Some(person_id)) .my_person_id(Some(person_id)) .show_bot_accounts(Some(show_bot_accounts)) diff --git a/crates/routes/src/images.rs b/crates/routes/src/images.rs index 788191a13..9b7801f2a 100644 --- a/crates/routes/src/images.rs +++ b/crates/routes/src/images.rs @@ -129,7 +129,7 @@ async fn full_res( context: web::Data, ) -> Result { // block access to images if instance is private and unauthorized, public - let local_site = LocalSite::read(context.conn().await?) + let local_site = LocalSite::read(context.pool()) .await .map_err(error::ErrorBadRequest)?; if local_site.private_instance { diff --git a/crates/routes/src/nodeinfo.rs b/crates/routes/src/nodeinfo.rs index d945a6251..124e1ea43 100644 --- a/crates/routes/src/nodeinfo.rs +++ b/crates/routes/src/nodeinfo.rs @@ -29,7 +29,7 @@ async fn node_info_well_known( } async fn node_info(context: web::Data) -> Result { - let site_view = SiteView::read_local(context.conn().await?) + let site_view = SiteView::read_local(context.pool()) .await .map_err(|_| ErrorBadRequest(LemmyError::from(anyhow!("not_found"))))?; diff --git a/crates/routes/src/webfinger.rs b/crates/routes/src/webfinger.rs index 7bda270ce..79de351a8 100644 --- a/crates/routes/src/webfinger.rs +++ b/crates/routes/src/webfinger.rs @@ -38,11 +38,11 @@ async fn get_webfinger_response( let name = extract_webfinger_name(&info.resource, &context)?; let name_ = name.clone(); - let user_id: Option = Person::read_from_name(context.conn().await?, &name_, false) + let user_id: Option = Person::read_from_name(context.pool(), &name_, false) .await .ok() .map(|c| c.actor_id.into()); - let community_id: Option = Community::read_from_name(context.conn().await?, &name, false) + let community_id: Option = Community::read_from_name(context.pool(), &name, false) .await .ok() .map(|c| c.actor_id.into()); diff --git a/src/code_migrations.rs b/src/code_migrations.rs index 8faeacf31..c69ce591c 100644 --- a/src/code_migrations.rs +++ b/src/code_migrations.rs @@ -7,6 +7,7 @@ use diesel::{ QueryDsl, TextExpressionMethods, }; +use diesel_async::RunQueryDsl; use lemmy_api_common::{ lemmy_db_views::structs::SiteView, utils::{ @@ -32,36 +33,34 @@ use lemmy_db_schema::{ site::{Site, SiteInsertForm, SiteUpdateForm}, }, traits::Crud, - utils::{naive_now, GetConn, RunQueryDsl}, + utils::{get_conn, naive_now, DbPool}, }; use lemmy_utils::{error::LemmyError, settings::structs::Settings}; use tracing::info; use url::Url; -pub async fn run_advanced_migrations( - mut conn: impl GetConn, - settings: &Settings, -) -> Result<(), LemmyError> { +pub async fn run_advanced_migrations(pool: &DbPool, settings: &Settings) -> Result<(), LemmyError> { let protocol_and_hostname = &settings.get_protocol_and_hostname(); - user_updates_2020_04_02(conn, protocol_and_hostname).await?; - community_updates_2020_04_02(conn, protocol_and_hostname).await?; - post_updates_2020_04_03(conn, protocol_and_hostname).await?; - comment_updates_2020_04_03(conn, protocol_and_hostname).await?; - private_message_updates_2020_05_05(conn, protocol_and_hostname).await?; - post_thumbnail_url_updates_2020_07_27(conn, protocol_and_hostname).await?; - apub_columns_2021_02_02(conn).await?; - instance_actor_2022_01_28(conn, protocol_and_hostname).await?; - regenerate_public_keys_2022_07_05(conn).await?; - initialize_local_site_2022_10_10(conn, settings).await?; + user_updates_2020_04_02(pool, protocol_and_hostname).await?; + community_updates_2020_04_02(pool, protocol_and_hostname).await?; + post_updates_2020_04_03(pool, protocol_and_hostname).await?; + comment_updates_2020_04_03(pool, protocol_and_hostname).await?; + private_message_updates_2020_05_05(pool, protocol_and_hostname).await?; + post_thumbnail_url_updates_2020_07_27(pool, protocol_and_hostname).await?; + apub_columns_2021_02_02(pool).await?; + instance_actor_2022_01_28(pool, protocol_and_hostname).await?; + regenerate_public_keys_2022_07_05(pool).await?; + initialize_local_site_2022_10_10(pool, settings).await?; Ok(()) } async fn user_updates_2020_04_02( - mut conn: impl GetConn, + pool: &DbPool, protocol_and_hostname: &str, ) -> Result<(), LemmyError> { use lemmy_db_schema::schema::person::dsl::{actor_id, local, person}; + let conn = &mut get_conn(pool).await?; info!("Running user_updates_2020_04_02"); @@ -86,7 +85,7 @@ async fn user_updates_2020_04_02( .last_refreshed_at(Some(naive_now())) .build(); - Person::update(conn, cperson.id, &form).await?; + Person::update(pool, cperson.id, &form).await?; } info!("{} person rows updated.", incorrect_persons.len()); @@ -95,10 +94,11 @@ async fn user_updates_2020_04_02( } async fn community_updates_2020_04_02( - mut conn: impl GetConn, + pool: &DbPool, protocol_and_hostname: &str, ) -> Result<(), LemmyError> { use lemmy_db_schema::schema::community::dsl::{actor_id, community, local}; + let conn = &mut get_conn(pool).await?; info!("Running community_updates_2020_04_02"); @@ -124,7 +124,7 @@ async fn community_updates_2020_04_02( .last_refreshed_at(Some(naive_now())) .build(); - Community::update(conn, ccommunity.id, &form).await?; + Community::update(pool, ccommunity.id, &form).await?; } info!("{} community rows updated.", incorrect_communities.len()); @@ -133,10 +133,11 @@ async fn community_updates_2020_04_02( } async fn post_updates_2020_04_03( - mut conn: impl GetConn, + pool: &DbPool, protocol_and_hostname: &str, ) -> Result<(), LemmyError> { use lemmy_db_schema::schema::post::dsl::{ap_id, local, post}; + let conn = &mut get_conn(pool).await?; info!("Running post_updates_2020_04_03"); @@ -154,7 +155,7 @@ async fn post_updates_2020_04_03( protocol_and_hostname, )?; Post::update( - conn, + pool, cpost.id, &PostUpdateForm::builder().ap_id(Some(apub_id)).build(), ) @@ -167,10 +168,11 @@ async fn post_updates_2020_04_03( } async fn comment_updates_2020_04_03( - mut conn: impl GetConn, + pool: &DbPool, protocol_and_hostname: &str, ) -> Result<(), LemmyError> { use lemmy_db_schema::schema::comment::dsl::{ap_id, comment, local}; + let conn = &mut get_conn(pool).await?; info!("Running comment_updates_2020_04_03"); @@ -188,7 +190,7 @@ async fn comment_updates_2020_04_03( protocol_and_hostname, )?; Comment::update( - conn, + pool, ccomment.id, &CommentUpdateForm::builder().ap_id(Some(apub_id)).build(), ) @@ -201,10 +203,11 @@ async fn comment_updates_2020_04_03( } async fn private_message_updates_2020_05_05( - mut conn: impl GetConn, + pool: &DbPool, protocol_and_hostname: &str, ) -> Result<(), LemmyError> { use lemmy_db_schema::schema::private_message::dsl::{ap_id, local, private_message}; + let conn = &mut get_conn(pool).await?; info!("Running private_message_updates_2020_05_05"); @@ -222,7 +225,7 @@ async fn private_message_updates_2020_05_05( protocol_and_hostname, )?; PrivateMessage::update( - conn, + pool, cpm.id, &PrivateMessageUpdateForm::builder() .ap_id(Some(apub_id)) @@ -237,10 +240,11 @@ async fn private_message_updates_2020_05_05( } async fn post_thumbnail_url_updates_2020_07_27( - mut conn: impl GetConn, + pool: &DbPool, protocol_and_hostname: &str, ) -> Result<(), LemmyError> { use lemmy_db_schema::schema::post::dsl::{post, thumbnail_url}; + let conn = &mut get_conn(pool).await?; info!("Running post_thumbnail_url_updates_2020_07_27"); @@ -267,7 +271,8 @@ async fn post_thumbnail_url_updates_2020_07_27( /// We are setting inbox and follower URLs for local and remote actors alike, because for now /// all federated instances are also Lemmy and use the same URL scheme. -async fn apub_columns_2021_02_02(mut conn: impl GetConn) -> Result<(), LemmyError> { +async fn apub_columns_2021_02_02(pool: &DbPool) -> Result<(), LemmyError> { + let conn = &mut get_conn(pool).await?; info!("Running apub_columns_2021_02_02"); { use lemmy_db_schema::schema::person::dsl::{inbox_url, person, shared_inbox_url}; @@ -324,11 +329,11 @@ async fn apub_columns_2021_02_02(mut conn: impl GetConn) -> Result<(), LemmyErro /// Before this point, there is only a single value in the site table which refers to the local /// Lemmy instance, so thats all we need to update. async fn instance_actor_2022_01_28( - mut conn: impl GetConn, + pool: &DbPool, protocol_and_hostname: &str, ) -> Result<(), LemmyError> { info!("Running instance_actor_2021_09_29"); - if let Ok(site_view) = SiteView::read_local(conn).await { + if let Ok(site_view) = SiteView::read_local(pool).await { let site = site_view.site; // if site already has public key, we dont need to do anything here if !site.public_key.is_empty() { @@ -343,7 +348,7 @@ async fn instance_actor_2022_01_28( .private_key(Some(Some(key_pair.private_key))) .public_key(Some(key_pair.public_key)) .build(); - Site::update(conn, site.id, &site_form).await?; + Site::update(pool, site.id, &site_form).await?; } Ok(()) } @@ -353,7 +358,8 @@ async fn instance_actor_2022_01_28( /// key field is empty, generate a new keypair. It would be possible to regenerate only the pubkey, /// but thats more complicated and has no benefit, as federation is already broken for these actors. /// https://github.com/LemmyNet/lemmy/issues/2347 -async fn regenerate_public_keys_2022_07_05(mut conn: impl GetConn) -> Result<(), LemmyError> { +async fn regenerate_public_keys_2022_07_05(pool: &DbPool) -> Result<(), LemmyError> { + let conn = &mut get_conn(pool).await?; info!("Running regenerate_public_keys_2022_07_05"); { @@ -374,7 +380,7 @@ async fn regenerate_public_keys_2022_07_05(mut conn: impl GetConn) -> Result<(), .public_key(Some(key_pair.public_key)) .private_key(Some(Some(key_pair.private_key))) .build(); - Community::update(conn, community_.id, &form).await?; + Community::update(pool, community_.id, &form).await?; } } @@ -396,7 +402,7 @@ async fn regenerate_public_keys_2022_07_05(mut conn: impl GetConn) -> Result<(), .public_key(Some(key_pair.public_key)) .private_key(Some(Some(key_pair.private_key))) .build(); - Person::update(conn, person_.id, &form).await?; + Person::update(pool, person_.id, &form).await?; } } Ok(()) @@ -407,13 +413,13 @@ async fn regenerate_public_keys_2022_07_05(mut conn: impl GetConn) -> Result<(), /// If a site already exists, the DB migration should generate a local_site row. /// This will only be run for brand new sites. async fn initialize_local_site_2022_10_10( - mut conn: impl GetConn, + pool: &DbPool, settings: &Settings, ) -> Result<(), LemmyError> { info!("Running initialize_local_site_2022_10_10"); // Check to see if local_site exists - if LocalSite::read(conn).await.is_ok() { + if LocalSite::read(pool).await.is_ok() { return Ok(()); } info!("No Local Site found, creating it."); @@ -423,7 +429,7 @@ async fn initialize_local_site_2022_10_10( .expect("must have domain"); // Upsert this to the instance table - let instance = Instance::read_or_create(conn, domain).await?; + let instance = Instance::read_or_create(pool, domain).await?; if let Some(setup) = &settings.setup { let person_keypair = generate_actor_keypair()?; @@ -444,14 +450,14 @@ async fn initialize_local_site_2022_10_10( .inbox_url(Some(generate_inbox_url(&person_actor_id)?)) .shared_inbox_url(Some(generate_shared_inbox_url(&person_actor_id)?)) .build(); - let person_inserted = Person::create(conn, &person_form).await?; + let person_inserted = Person::create(pool, &person_form).await?; let local_user_form = LocalUserInsertForm::builder() .person_id(person_inserted.id) .password_encrypted(setup.admin_password.clone()) .email(setup.admin_email.clone()) .build(); - LocalUser::create(conn, &local_user_form).await?; + LocalUser::create(pool, &local_user_form).await?; }; // Add an entry for the site table @@ -473,14 +479,14 @@ async fn initialize_local_site_2022_10_10( .private_key(Some(site_key_pair.private_key)) .public_key(Some(site_key_pair.public_key)) .build(); - let site = Site::create(conn, &site_form).await?; + let site = Site::create(pool, &site_form).await?; // Finally create the local_site row let local_site_form = LocalSiteInsertForm::builder() .site_id(site.id) .site_setup(Some(settings.setup.is_some())) .build(); - let local_site = LocalSite::create(conn, &local_site_form).await?; + let local_site = LocalSite::create(pool, &local_site_form).await?; // Create the rate limit table let local_site_rate_limit_form = LocalSiteRateLimitInsertForm::builder() @@ -496,7 +502,7 @@ async fn initialize_local_site_2022_10_10( .search(Some(999)) .local_site_id(local_site.id) .build(); - LocalSiteRateLimit::create(conn, &local_site_rate_limit_form).await?; + LocalSiteRateLimit::create(pool, &local_site_rate_limit_form).await?; Ok(()) } diff --git a/src/lib.rs b/src/lib.rs index e77a02d34..f84842fe0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -21,7 +21,7 @@ use lemmy_api_common::{ use lemmy_apub::{VerifyUrlData, FEDERATION_HTTP_FETCH_LIMIT}; use lemmy_db_schema::{ source::secret::Secret, - utils::{build_db_pool, get_conn, get_database_url, run_migrations}, + utils::{build_db_pool, get_database_url, run_migrations}, }; use lemmy_routes::{feeds, images, nodeinfo, webfinger}; use lemmy_utils::{error::LemmyError, rate_limit::RateLimitCell, settings::SETTINGS}; @@ -55,15 +55,15 @@ pub async fn start_lemmy_server() -> Result<(), LemmyError> { let pool = build_db_pool(&settings).await?; // Run the Code-required migrations - run_advanced_migrations(get_conn(&pool).await?, &settings).await?; + run_advanced_migrations(&pool, &settings).await?; // Initialize the secrets - let secret = Secret::init(get_conn(&pool).await?) + let secret = Secret::init(&pool) .await .expect("Couldn't initialize secrets."); // Make sure the local site is set up. - let site_view = SiteView::read_local(get_conn(&pool).await?) + let site_view = SiteView::read_local(&pool) .await .expect("local site not set up"); let local_site = site_view.local_site;