Transactions, Triggers and Error Messages

From: lh1101(at)ecs(dot)soton(dot)ac(dot)uk
To: pgsql-general(at)postgresql(dot)org
Subject: Transactions, Triggers and Error Messages
Date: 2005-11-08 22:09:17
Message-ID: 1131487757.4371220de3e52@webmail.soton.ac.uk
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Hi,

I am trying to use triggers inside transactions to perform some multiplicity
checking on the data inserted onto the tables but I am having some problems
retrieving the error message.

I have two tables declared as follows:

>>>>>>>>>>>>>>>>>>>>>
create table pers (
pid int not null primary key,
pname text not null
);

create table tasks (
taskid serial not null primary key,
pid int not null constraint tasks__ref_p references pers deferrable,
task text not null
);
>>>>>>>>>>>>>>>>>>>>>

My function and trigger are as below:

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
create function check_mult() returns trigger as $$
declare
cnt integer := 0;
begin
select count(*) into cnt from tasks where pid=new.pid;
if cnt>2 then
raise exception '3 tasks already exists for person with pid %',
new.pid;
end if;
return new;
end;
$$ language plpgsql;

create trigger ass_mult before insert or update on tasks for each row
execute procedure check_mult();
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Now when I run the following (after inserting person with id=5 into pers
table):

>>>>>>>>>>>>>>>>>>
begin;
set constraints all deferred;
insert into tasks (pid, task) values (5, 'firstTask');
insert into tasks (pid, task) values (5, 'secondTask');
insert into tasks (pid, task) values (5, 'thirdTask');
insert into tasks (pid, task) values (5, 'forthTask');
insert into tasks (pid, task) values (5, 'fifthTask');
commit;
>>>>>>>>>>>>>>>>>>

the transaction is correctly aborted but the error message I get is not the
one that raised the exception ie "3 tasks already exists for person with
pid 5" but the one from trying to insert the fifth task (ie last statement)
which is "ERROR: current transaction is aborted, commands ignored until
end of transaction block"

Is there anyway I can stop the transaction after the exception is raised so
that I can retrieve the correct error message?

I know rollbacks inside triggers are simply ignored (I tried that) but I
thought maybe there was another way.

Thank you in advance for any help,
Ledina

PS My transactions have to be deferred by that shouldn't make a difference

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2005-11-08 22:12:52 Re: [HACKERS] Troubles with array_ref
Previous Message Keith C. Perry 2005-11-08 21:56:40 clustering by partial indexes