BUG #14870: wrong query results when using WITH with UPDATE

andreigorita@gmail.com

From: andreigorita@gmail.com
To: pgsql-bugs@postgresql.org
Cc: andreigorita@gmail.com
Date: 2017-10-24T15:53:58Z
Lists: pgsql-bugs

Commits

Same data as JSON: GET /api/v1/messages/:b64id/commits the thread's linked commits as JSON, with link sources. API reference →
  1. Fix misbehavior of CTE-used-in-a-subplan during EPQ rechecks.

The following bug has been logged on the website:

Bug reference:      14870
Logged by:          Andrei Gorita
Email address:      andreigorita@gmail.com
PostgreSQL version: 9.6.1
Operating system:   CentOS
Description:        

when updating a table with unique index within a WITH part of a query, in
certain conditions the query reports that updated more than one row.

A simple way to reproduce:

test=> create table tmp_test(id int not null, test text not null);
CREATE TABLE
test=> create unique index on tmp_test(id);
CREATE INDEX
test=> INSERT INTO tmp_test VALUES (1, 'test');
INSERT 0 1
test=> create table tmp_test2(id int not null, test text not null);
CREATE TABLE

test=> WITH updated AS (UPDATE tmp_test SET test = 'test' WHERE id = 1
RETURNING id), inserted AS (INSERT INTO tmp_test2 (id, test) SELECT 1,
'test' WHERE NOT EXISTS (SELECT 1 FROM updated) RETURNING id) SELECT * FROM
updated;
 id 
----
  1
(1 row)

This is the expected result, but when another session is executing in
parallel:
test=> begin;
BEGIN
test=> UPDATE tmp_test SET test = 'test' WHERE id = 1;
UPDATE 1
test=> commit;
COMMIT


the result is:

test=> WITH updated AS (UPDATE tmp_test SET test = 'test' WHERE id = 1
RETURNING id), inserted AS (INSERT INTO tmp_test2 (id, test) SELECT 1,
'test' WHERE NOT EXISTS (SELECT 1 FROM updated) RETURNING id) SELECT * FROM
updated;
 id 
----
  1
  1
(2 rows)

which is at least strange.