Re: atomic multi-threaded upsert

From: KM <km(at)xacrasis(dot)netx>
To: pgsql-sql(at)postgresql(dot)org
Subject: Re: atomic multi-threaded upsert
Date: 2010-11-25 02:12:00
Message-ID: 4cedc5f0$0$22107$742ec2ed@news.sonic.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On 2010-11-24, "Mikhail V. Puzanov" <misha(dot)puzanov(at)gmail(dot)com> wrote:
> Next, I execute the following two queries for that table:
>
> -- increment and get the counter if exists
> UPDATE sequences SET counter = counter + 1
> WHERE section = 'testSection' AND name = 'testKey'
> RETURNING counter;
>
> -- insert new counter if not exists
> INSERT INTO sequences ( section, name, counter )
> SELECT 'testSection', 'testKey', 0
> WHERE NOT EXISTS (
> SELECT * FROM sequences
> WHERE section = 'testSection' AND name = 'testKey'
> );

> ERROR: duplicate key value violates unique constraint "idx_sequences_sn"
>
> 1) That looks weird actually, should the INSERT ... NOT EXISTS (...) be
> executed
> in atomic fashion? Also, AFAIK, UNIQUE INDEX locks rows before
> insert (or not?).
> Can it be related to JDBC?
> Or it's the result of MVCC conflict resolution?

Perhaps -

Thread A UPDATEs, affecting no row.
Thread B UPDATEs, affecting no row.
Thread A INSERTs one row. Autocommit is on, so it commits the INSERT.
Thread B attempts INSERT and fails on the duplicate.

--
KM

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Chang Chao 2010-11-25 05:42:26 How strings are sorted by LC_COLLATE specifically?
Previous Message Adrian Klaver 2010-11-25 00:25:15 Re: insert from a select