aboutsummaryrefslogtreecommitdiffstats
path: root/crates/turtle/db/server-pg-migrations/20220421073605_fix_count_trigger_delete.sql
blob: 6198f30018cb1db6a7cf34cf62abafd7f63a895d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
-- the old version of this function used NEW in the delete part when it should
-- use OLD

create or replace function user_history_count()
returns trigger as 
$func$
begin
	if (TG_OP='INSERT') then
		update total_history_count_user set total = total + 1 where user_id = new.user_id;

		if not found then
			insert into total_history_count_user(user_id, total) 
			values (
				new.user_id, 
				(select count(1) from history where user_id = new.user_id)
			);
		end if;
		
	elsif (TG_OP='DELETE') then
		update total_history_count_user set total = total - 1 where user_id = old.user_id;

		if not found then
			insert into total_history_count_user(user_id, total) 
			values (
				old.user_id, 
				(select count(1) from history where user_id = old.user_id)
			);
		end if;
	end if;

	return NEW; -- this is actually ignored for an after trigger, but oh well
end;
$func$
language plpgsql volatile -- pldfplplpflh
cost 100; -- default value