1 -- Fix for duplicated decrementations when both `deleted` and `removed` fields are set subsequently
2 create or replace function was_removed_or_deleted(TG_OP text, OLD record, NEW record)
7 IF (TG_OP = 'INSERT') THEN
11 IF (TG_OP = 'DELETE' AND OLD.deleted = 'f' AND OLD.removed = 'f') THEN
15 return TG_OP = 'UPDATE' AND OLD.deleted = 'f' AND OLD.removed = 'f' AND (
16 NEW.deleted = 't' OR NEW.removed = 't'
20 create or replace function was_restored_or_created(TG_OP text, OLD record, NEW record)
25 IF (TG_OP = 'DELETE') THEN
29 IF (TG_OP = 'INSERT') THEN
33 return TG_OP = 'UPDATE' AND NEW.deleted = 'f' AND NEW.removed = 'f' AND (
34 OLD.deleted = 't' OR OLD.removed = 't'
38 -- Fix for post's comment count not updating after setting `removed` to 't'
39 drop trigger if exists post_aggregates_comment_set_deleted on comment;
40 drop function post_aggregates_comment_deleted();
42 create or replace function post_aggregates_comment_count()
43 returns trigger language plpgsql
46 -- Check for post existence - it may not exist anymore
47 IF TG_OP = 'INSERT' OR EXISTS (
48 select 1 from post p where p.id = OLD.post_id
50 IF (was_restored_or_created(TG_OP, OLD, NEW)) THEN
51 update post_aggregates pa
52 set comments = comments + 1 where pa.post_id = NEW.post_id;
53 ELSIF (was_removed_or_deleted(TG_OP, OLD, NEW)) THEN
54 update post_aggregates pa
55 set comments = comments - 1 where pa.post_id = OLD.post_id;
59 IF TG_OP = 'INSERT' THEN
60 update post_aggregates pa
61 set newest_comment_time = NEW.published
62 where pa.post_id = NEW.post_id;
64 -- A 2 day necro-bump limit
65 update post_aggregates pa
66 set newest_comment_time_necro = NEW.published
68 where pa.post_id = p.id
69 and pa.post_id = NEW.post_id
70 -- Fix issue with being able to necro-bump your own post
71 and NEW.creator_id != p.creator_id
72 and pa.published > ('now'::timestamp - '2 days'::interval);
78 create or replace trigger post_aggregates_comment_count
79 after insert or delete or update of removed, deleted on comment
81 execute procedure post_aggregates_comment_count();