Re: Query on exception handling in PL/pgSQL

Поиск
Список
Период
Сортировка
От Joachim Zobel
Тема Re: Query on exception handling in PL/pgSQL
Дата
Msg-id 1101559218.3549.10.camel@localhost
обсуждение исходный текст
Ответ на Query on exception handling in PL/pgSQL  (diya das <diyadas@yahoo.com>)
Список 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 по дате отправления:

Предыдущее
От: Martijn van Oosterhout
Дата:
Сообщение: Re: row-level deadlock problem
Следующее
От: Joachim Zobel
Дата:
Сообщение: Debian Packages for 8.0