Re: Query on exception handling in PL/pgSQL

From: Joachim Zobel <jzobel(at)heute-morgen(dot)de>
To: pgsql-general(at)postgresql(dot)org
Subject: Re: Query on exception handling in PL/pgSQL
Date: 2004-11-27 12:40:18
Message-ID: 1101559218.3549.10.camel@localhost
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: 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

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Joachim Zobel 2004-11-27 12:42:33 Debian Packages for 8.0
Previous Message Martijn van Oosterhout 2004-11-27 12:03:36 Re: row-level deadlock problem