Re: Query on exception handling in PL/pgSQL - Mailing list pgsql-general

From Joachim Zobel
Subject Re: Query on exception handling in PL/pgSQL
Date
Msg-id 1101559218.3549.10.camel@localhost
Whole thread Raw
In response to Query on exception handling in PL/pgSQL  (diya das <diyadas@yahoo.com>)
List pgsql-general
Am Fr, den 26.11.2004 schrieb diya das um 14:28:
>   I am just a beginner in postgreSQL and writing some
> functions in PL/pgSQL. I use the libpq interface in
> the client to call this funtions.  My pgsql function
> does an insert to a table and I have opened a
> transaction block before calling my function from the
> client. When the insert operation fails due to unique
> key violation the whole transaction aborts. Is there a
> way I can handle this error in my pgsql funtion rather
> that aborting and not executing the rest of the
> operations?. I have a workaround , But I was wondering
> if there is an inexpensive way of doing it.

Probably you want to do a write operation (UPDATE if the record exists,
INSERT otherwise). You should be aware that trying the INSERT first and
then UPDATEing if it fails is a bad way to do this. If the constraint is
ever accidentially turned of, your data gets corrupted. Provoking
exceptions for situations that are not exceptional is IMHO bad
programming practice anyway.

The good way is either (portable) to do a SELECT to check for existence
of the record or to do the UPDATE first and check FOUND:

UPDATE ...
WHERE key=$1

IF NOT FOUND THEN
  INSERT...
END IF;

Sincerely,
Joachim

--
"... ein Geschlecht erfinderischer Zwerge, die fuer alles gemietet werden
koennen."                            - Bertolt Brecht - Leben des Galilei


pgsql-general by date:

Previous
From: Martijn van Oosterhout
Date:
Subject: Re: row-level deadlock problem
Next
From: Joachim Zobel
Date:
Subject: Debian Packages for 8.0