From: Sebastien Flaesch <sebastien.flaesch@4js.com>
To: pgsql-general <pgsql-general@lists.postgresql.org>
Subject: Concurrent INSERT statements with RETURNING clause resetting SERIAL sequence
Date: Tue, 19 Jul 2022 15:33:52 +0000
Message-ID: <DBAP191MB1289AC6BB681A44166256884B08F9@DBAP191MB1289.EURP191.PROD.OUTLOOK.COM> (raw)
Hello!
I try to update the underlying sequence of a SERIAL column, by using a RETURNING clause in my INSERT statement, which is checking that the column value is greater than the last_value of my sequence, and reset the sequence with setval() if needed.
When running several client processes in concurrently, using this INSERT statement, I get duplicate primary key errors.
The SQL code of my INSERT looks like this:
insert into tab1 (name) VALUES ('aaa')
returning tab1.pkey,
(select case
when tab1.pkey>=(select last_value from public.tab1_pkey_seq)
then setval('public.tab1_pkey_seq',tab1.pkey,true)
else 0
end)
To me something is wrong with the behavior of PostgreSQL:
The whole INSERT statement (including the code in the RETURNING clause), should execute in a ATOMIC manner.
Obviously if several processes execute that code in parallel, and if the select last_value / setval() get mixed up, we are in trouble...
Can something confirm this is a PostgreSQL bug, or help me to find the right code to avoid the issue?
To reproduce:
1. Create tab1 table and stored procedure for testing with insert-tab1.sql
2. Run several psql processes in parallel, calling the stored procedure: sh ./start2.sh (Linux/bash)
Thanks!
Seb
Attachments:
inserts-tab1.sql (application/sql, 773B) download
call-proc.sql (application/sql, 31B) download
start2.sh (application/x-shellscript, 582B) download
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-general@postgresql.org
Cc: sebastien.flaesch@4js.com
Subject: Re: Concurrent INSERT statements with RETURNING clause resetting SERIAL sequence
In-Reply-To: <DBAP191MB1289AC6BB681A44166256884B08F9@DBAP191MB1289.EURP191.PROD.OUTLOOK.COM>
References: <DBAP191MB1289AC6BB681A44166256884B08F9@DBAP191MB1289.EURP191.PROD.OUTLOOK.COM>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox