Skip to content

Commit 2db4108

Browse files
add club rating refresh migration files
1 parent e8c6ac7 commit 2db4108

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
BEGIN;
2+
3+
-- Drop triggers on the club_ratings table
4+
DROP TRIGGER IF EXISTS trg_club_ratings_ins ON club_ratings;
5+
DROP TRIGGER IF EXISTS trg_club_ratings_upd ON club_ratings;
6+
DROP TRIGGER IF EXISTS trg_club_ratings_del ON club_ratings;
7+
8+
-- Drop the refresh function
9+
DROP FUNCTION IF EXISTS refresh_club_rating_agg();
10+
11+
COMMIT;
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
BEGIN;
2+
CREATE OR REPLACE FUNCTION refresh_club_rating_agg() RETURNS TRIGGER AS $$
3+
BEGIN
4+
UPDATE clubs c SET
5+
rating = COALESCE(sub.avg_rating, 0),
6+
ratings_count = COALESCE(sub.cnt, 0)
7+
FROM (
8+
SELECT club_id, AVG(rating)::float AS avg_rating, COUNT(*) AS cnt
9+
FROM club_ratings
10+
WHERE club_id = NEW.club_id
11+
GROUP BY club_id
12+
) sub
13+
WHERE c.id = NEW.club_id;
14+
RETURN NULL;
15+
END; $$ LANGUAGE plpgsql;
16+
17+
CREATE TRIGGER trg_club_ratings_ins
18+
AFTER INSERT ON club_ratings
19+
FOR EACH ROW EXECUTE FUNCTION refresh_club_rating_agg();
20+
21+
CREATE TRIGGER trg_club_ratings_upd
22+
AFTER UPDATE ON club_ratings
23+
FOR EACH ROW EXECUTE FUNCTION refresh_club_rating_agg();
24+
25+
CREATE TRIGGER trg_club_ratings_del
26+
AFTER DELETE ON club_ratings
27+
FOR EACH ROW EXECUTE FUNCTION refresh_club_rating_agg();
28+
COMMIT;

0 commit comments

Comments
 (0)