I'm trying to find a good way to return error messages from postgresql back to my client-side application. I've read about RAISE, which appears to be what I want, but I have couple questions. Using Postgresql 9.1.
An overview of what's going on, I'm receiving a JSON object from the client, parse the JSON into a Perl Hash, loop through the keys and do an update/insert on each iteration. The hash keys correlate with the my database table names.
I have 3 sql functions like this (all the same name). One accepts text,timestamp with timezone, and an integer. (query used from https://stackoverflow.com/a/6527838/722238)
-- $1 = Table Key, $2 = Table Value, $3 = Table Name.
create function ex.foo(integer,text,text) Arg2 could be timestamp,text,or integer.
returns void as $$
begin
execute format('update %3$s set v= %2$L where k = %1$L;
insert into %3$s (k,v) select %1$s, %2$L
where not exists (select 1 from %3$s where k = %1$L)', $1,$2,$3);
-- RAISE a descriptive error.
return;
end;
$$ language 'plpgsql';
At the moment, I'm doing this (pseudo-ish code):
if (Begin) {
eval {
my $tk = 123;
foreach my $k (keys %js) {
## tk = table key, $k = table name, $js{$k} = value
executeq("select ex.foo(tk,$js{$k},$k);") or die error(pgError); # Function to handle error?
}
Commit;
};
if ($@) {
RollBack;
## Return $@
}
}
My problem is, I'm not sure how I should generate a descriptive error (where/why), return it up the chain and in language the user can understand. Again, how should I raise the error, and should it be passed to an error handler function? What is the standard? How do others achieve this?
Also, are there issues I may run into while looping through my hash and insert/updating values like this?