
create table testsource
(	
	id serial primary key,
	company int,
	data text
);

create table testsummary
(
	company int primary key,
	source_id int references testsource(id)
		on delete cascade,
	data text
);


create or replace function trignotice()
returns trigger
as $$
BEGIN
	raise notice '% - OP: % REL: % WHEN: %', TG_ARGV[0], 
			TG_OP, TG_RELNAME, TG_WHEN;
	
	if TG_OP = 'DELETE' then
		return OLD;
	else
		return NEW;
	end if;
END
$$
language 'plpgsql';

create or replace function testupdatesummary()
returns trigger
as $$
DECLARE
	v_c int;
	v_i int;
BEGIN
	raise notice 'update summary'; 

	if TG_OP = 'DELETE' then
		v_c := OLD.company;
		v_i := null;
	else
		v_c := NEW.company;
		v_i := NEW.id;
	end if;
	
	delete from testsummary
		where company = v_c;
		
	insert into testsummary (company, source_id)
		values (v_c, v_i);
	
	return null;
END
$$
language 'plpgsql';
	
create trigger a_logtrigger 
	after insert or delete or update on testsource 
	for each row execute procedure trignotice('logger');

create trigger b_summary
	after insert or delete or update on testsource
	for each row execute procedure testupdatesummary('summaryupdate');

create trigger b_summary_before
	before insert or delete or update on testsummary
	for each row execute procedure trignotice('tabaction');

create trigger b_summary_after
	after insert or delete or update on testsummary
	for each row execute procedure trignotice('tabaction');
	
create trigger a_logtrigger
	after insert or delete or update on testsummary
	for each row execute procedure trignotice('logger');
	
insert into testsource(company) values (1);
delete from testsource where company = 1;

--drop table testsummary;
--drop table testsource;

--drop function trignotice();
--drop function testupdatesummary();


