From 0f17a163824efbd9c950e5f8dcec9a6ac8bc6391 Mon Sep 17 00:00:00 2001 From: Tom Russell Date: Sun, 20 Jan 2019 14:36:15 +0000 Subject: [PATCH] Drop duplicate likes and reset counts --- migrations/005.limit-likes.up.sql | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/migrations/005.limit-likes.up.sql b/migrations/005.limit-likes.up.sql index 3581b2f2..2ef7801a 100644 --- a/migrations/005.limit-likes.up.sql +++ b/migrations/005.limit-likes.up.sql @@ -1,2 +1,26 @@ +-- -- One like per-building, per-user +-- + +-- Drop duplicate likes +DELETE FROM building_user_likes + WHERE building_like_id NOT IN ( + SELECT min(building_like_id) + FROM building_user_likes + GROUP BY (building_id, user_id) + ); + +-- Reset counts +UPDATE buildings + SET likes_total = ( + SELECT count(*) + FROM building_user_likes + WHERE buildings.building_id = building_user_likes.building_id + ) + WHERE buildings.building_id in ( + SELECT DISTINCT building_id + FROM building_user_likes + ); + +-- Add constraint ALTER TABLE building_user_likes ADD CONSTRAINT building_like_once UNIQUE (building_id, user_id);