Re: How to capture and handle failed INSERT

Поиск
Список
Период
Сортировка
От Berend Tober
Тема Re: How to capture and handle failed INSERT
Дата
Msg-id 45EB3725.3000209@ct.metrocast.net
обсуждение исходный текст
Ответ на How to capture and handle failed INSERT  ("Postgres User" <postgres.developer@gmail.com>)
Ответы Re: How to capture and handle failed INSERT  ("Postgres User" <postgres.developer@gmail.com>)
Список pgsql-general
Postgres User wrote:
> I'm using this code to increment a counter table:
>
> IF Exists (SELECT keyfld FROM counter_tbl WHERE key_fld = 'key_val') THEN
>    UPDATE counter_tbl SET  counter_fld = counter_fld + 1
>          WHERE key_fld = 'key_val';
>  ELSE
>    INSERT INTO counter_tbl(key_fld, counter_fld) VALUES('key_val', 1);
> END IF;
>
> Now, I assume that it's possible for another session to INSERT a row
> in the microseconds that exist between the Select and Insert
> statements above.
>
> I also assume that I can wrap the above code in a transaction, and if
> the transaction fails (because another session's Insert causes my
> Insert to fail), then I simply need to re-execute it once. (Updates
> should never fail.)
>
> Does anyone have a simple example of the best way to code this type of
> transaction- and the best way to re-execute the same code on failure?
> I could use a loop but I'm not sure if that's the best solution.

I think I would try the INSERT first. If it fails, then trap the
exception and do the UPDATE


В списке pgsql-general по дате отправления:

Предыдущее
От: Devrim GÜNDÜZ
Дата:
Сообщение: Re: real multi-master replication?
Следующее
От: "Postgres User"
Дата:
Сообщение: Re: How to capture and handle failed INSERT