I am trying to run the following query:
WITH upd AS (
UPDATE fila_all SET id = id WHERE
id = (select id from fila_all fa where fa.id not in (select msg_id from fila_consumers where group_name = 'group0') and fa.queue_name = 'myqueue' order by id asc limit 1 for update of fa skip locked)
returning id
)
INSERT INTO fila_consumers select fa2.id, 'new-worker0', 'group0', 'Running'
FROM fila_all fa2 JOIN upd on upd.id = fa2.id
RETURNING msg_id
id is a primary key on fila_all, and (msg_id, group_name) is a primary key on fila_consumers.
fila_consumers only has four columns, id bigint, worker_name varchar, group varchar, status enum.
I would expect this query to never fail due to a conflict on fila_consumers_pk, because the rows are locked, and skipped, on the update, so two transactions cannot get the same fila_all.id for insertion in fila_consumers. But I get the following error:
duplicate key value violates unique constraint "fila_consumers_pkey"
Detail: Key (msg_id, group_name)=[...]
I don't want to use ON CONFLICT DO NOTHING, I'd like to understand why this is happening.
All insertions on fila_consumers are based on this statement, multiple instances of this statement run concurrently, but no other statements are executed that insert on this table.
What am I missing here? Is there a way around this?
fila_consumers only has tree columns. But you are inserting 4 expressions:INSERT INTO fila_consumers select fa2.id, 'new-worker0', 'group0', 'Running'. And the quoted error msg. disagrees, too:Key (msg_id, group_name). Please clarify. – Erwin Brandstetter Jul 15 '21 at 11:02