Skip to content

Instantly share code, notes, and snippets.

@hgmnz
Created November 7, 2009 17:18
Show Gist options
  • Save hgmnz/228786 to your computer and use it in GitHub Desktop.
Save hgmnz/228786 to your computer and use it in GitHub Desktop.
create table count_cache (
id serial primary key,
table_name varchar(255) not null,
count int not null
)
create table people (
id serial primary key,
name varchar(255) not null
)
-- insert trigger
create or replace function log_count_insert() returns trigger as $end$
begin
update count_cache set count = count + 1 where table_name = TG_RELNAME;
return null; -- no return on an after trigger
end;
$end$ language plpgsql;
create trigger people_insert_count after insert on people
for each row execute procedure log_count_insert();
alter table people enable trigger people_insert_count;
-- delete trigger
create or replace function log_count_delete() returns trigger as $end$
begin
update count_cache set count = count - 1 where table_name = TG_RELNAME;
return null; -- no return on after trigger
end;
$end$ language plpgsql;
create trigger people_delete_count after delete on people
for each row execute procedure log_count_delete();
alter table people enable trigger people_delete_count;
--initialize on count_cache, this must be done for each table that caches the count
insert into count_cache(table_name, count) values ('people', 0)
insert into people (name) values ('john');
insert into people (name) values ('john');
insert into people (name) values ('jay');
insert into people (name) values ('mustang');
insert into people (name) values ('sally');
insert into people (name) values ('fred');
select count from count_cache where table_name = 'people';
select count(*) from people;
-- => 6
delete from people where name = 'john';
select count from count_cache where table_name = 'people'
select count(*) from people;
-- => 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment