veza/veza-backend-api/migrations/125_follow_counts_triggers.sql

48 lines
1.7 KiB
PL/PgSQL

-- 125_follow_counts_triggers.sql
-- v0.10.0 F187: Denormalized follower/following counts in user_profiles
-- Triggers to update user_profiles.follower_count and following_count on follows insert/delete
-- Increment follower_count for followed user, following_count for follower
CREATE OR REPLACE FUNCTION increment_follow_counts()
RETURNS TRIGGER AS $$
BEGIN
UPDATE public.user_profiles
SET follower_count = follower_count + 1
WHERE user_id = NEW.followed_id;
UPDATE public.user_profiles
SET following_count = following_count + 1
WHERE user_id = NEW.follower_id;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- Decrement with floor at 0 to prevent negative counts
CREATE OR REPLACE FUNCTION decrement_follow_counts()
RETURNS TRIGGER AS $$
BEGIN
UPDATE public.user_profiles
SET follower_count = GREATEST(0, follower_count - 1)
WHERE user_id = OLD.followed_id;
UPDATE public.user_profiles
SET following_count = GREATEST(0, following_count - 1)
WHERE user_id = OLD.follower_id;
RETURN OLD;
END;
$$ LANGUAGE plpgsql;
DROP TRIGGER IF EXISTS trg_follows_insert_counts ON public.follows;
CREATE TRIGGER trg_follows_insert_counts
AFTER INSERT ON public.follows
FOR EACH ROW EXECUTE FUNCTION increment_follow_counts();
DROP TRIGGER IF EXISTS trg_follows_delete_counts ON public.follows;
CREATE TRIGGER trg_follows_delete_counts
AFTER DELETE ON public.follows
FOR EACH ROW EXECUTE FUNCTION decrement_follow_counts();
COMMENT ON FUNCTION increment_follow_counts() IS 'v0.10.0 F187: Update user_profiles counts on follow';
COMMENT ON FUNCTION decrement_follow_counts() IS 'v0.10.0 F187: Update user_profiles counts on unfollow';