Re: Catching DML exceptions in PL/pgSQL - Mailing list pgsql-sql

From Joe Conway
Subject Re: Catching DML exceptions in PL/pgSQL
Date
Msg-id 3EEEE5CE.1000509@joeconway.com
Whole thread Raw
In response to Catching DML exceptions in PL/pgSQL  (Radu-Adrian Popescu <radu.popescu@aldratech.com>)
Responses Re: Catching DML exceptions in PL/pgSQL
List pgsql-sql
Radu-Adrian Popescu wrote:
> .....................
> begin
>     _res.code:=1;
>     select id into iid from log where id=_id;
>     if not found then begin
>         _res.msg:=''insert'';
>         *insert into log (log, data) values (_log, _data);
>         if not found* then begin
>             _res.msg:=_res.msg || '' error'';
>             _res.code:=-1;
>         end;
>         end if;
>     end;
>     else begin
> .....................
> The thing is if _data (parameter) is null and table has a (data <> null) check, 
> the insert would fail and abort the function before my "if not found" test.

You could test for _data is null, and if so check attnotnull in 
pg_attribute. E.g. something like:

declare  iattnotnull bool
[...]
begin  if _data is null then    select into iattnotnull attnotnull from pg_catalog.pg_attribute    where attrelid =
'log'::regclassand attname = 'data';    if iattnotnull then      _res.code := -1;      [...]
 

> Is there anything I can do to make sure the function always returns _res ?
> Something along the lines of Oracle's exception handling, or the @@error trick 
> in mssql ?

There is currently no way to "catch" the exception in PL/pgSQL, but 
maybe the above would work for you.

HTH,

Joe



pgsql-sql by date:

Previous
From: Radu-Adrian Popescu
Date:
Subject: Re: Catching DML exceptions in PL/pgSQL
Next
From: Radu-Adrian Popescu
Date:
Subject: Re: Catching DML exceptions in PL/pgSQL