From 007e9b7aabe859faeacc7b3128ddc57fe930a308 Mon Sep 17 00:00:00 2001 From: dullbananas Date: Tue, 2 Apr 2024 08:19:04 -0700 Subject: [PATCH] Optimize Community::set_featured_posts (#4579) * Don't lock excess rows in Community::set_featured_posts * Update community.rs * Update community.rs * Update community.rs * Update community.rs --- crates/db_schema/src/impls/community.rs | 35 ++++++++----------------- 1 file changed, 11 insertions(+), 24 deletions(-) diff --git a/crates/db_schema/src/impls/community.rs b/crates/db_schema/src/impls/community.rs index dbacbcb72..af3bf9bcf 100644 --- a/crates/db_schema/src/impls/community.rs +++ b/crates/db_schema/src/impls/community.rs @@ -29,6 +29,7 @@ use diesel::{ select, sql_types, update, + BoolExpressionMethods, ExpressionMethods, NullableExpressionMethods, QueryDsl, @@ -150,30 +151,16 @@ impl Community { for p in &posts { debug_assert!(p.community_id == community_id); } - conn - .build_transaction() - .run(|conn| { - Box::pin(async move { - update( - // first remove all existing featured posts - post::table, - ) - .filter(post::dsl::community_id.eq(community_id)) - .set(post::dsl::featured_community.eq(false)) - .execute(conn) - .await?; - - // then mark the given posts as featured - let post_ids: Vec<_> = posts.iter().map(|p| p.id).collect(); - update(post::table) - .filter(post::dsl::id.eq_any(post_ids)) - .set(post::dsl::featured_community.eq(true)) - .execute(conn) - .await?; - Ok(()) - }) as _ - }) - .await + // Mark the given posts as featured and all other posts as not featured. + let post_ids = posts.iter().map(|p| p.id); + update(post::table) + .filter(post::dsl::community_id.eq(community_id)) + // This filter is just for performance + .filter(post::dsl::featured_community.or(post::dsl::id.eq_any(post_ids.clone()))) + .set(post::dsl::featured_community.eq(post::dsl::id.eq_any(post_ids))) + .execute(conn) + .await?; + Ok(()) } }