RE: BUG #19069: pg_advisory_xact_lock() in a WITH query doesn't work

From: Maciej Walczak <m(dot)walczak(at)megavision(dot)pl>
To: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Cc: "pgsql-bugs(at)lists(dot)postgresql(dot)org" <pgsql-bugs(at)lists(dot)postgresql(dot)org>
Subject: RE: BUG #19069: pg_advisory_xact_lock() in a WITH query doesn't work
Date: 2025-10-03 09:34:39
Message-ID: ae57b96787364f5892fb86e85e9e7118@megavision.pl
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

Thank you.
I missed those parts of the documentation. I should have studied it more carefully.

The reason I tried to use WITH is that a separate

SELECT pg_advisory_xact_lock(1);

statement confuses my object mapper (Dapper) when I want to use a RETURNING clause in the INSERT.
I found a workaround:

DO $$ BEGIN
PERFORM pg_advisory_xact_lock(1);
END $$;

Regards
Maciej Walczak

-----Original Message-----
From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Sent: 02 October 2025 22:14
To: Maciej Walczak <m(dot)walczak(at)megavision(dot)pl>
Cc: pgsql-bugs(at)lists(dot)postgresql(dot)org
Subject: Re: BUG #19069: pg_advisory_xact_lock() in a WITH query doesn't work

PG Bug reporting form <noreply(at)postgresql(dot)org> writes:
> This doesn't actually do any locking:

> BEGIN;
> WITH my_lock AS (
> SELECT pg_advisory_xact_lock(1)
> )
> INSERT INTO my_table (...) VALUES (...); COMMIT;

That looks as-expected to me. The docs say [1]

[ This works because ] PostgreSQL's implementation evaluates only
as many rows of a WITH query as are actually fetched by the parent
query.

which is to say, none at all in this case. There's also this in [2]:

Data-modifying statements in WITH are executed exactly once, and
always to completion, independently of whether the primary query
reads all (or indeed any) of their output. Notice that this is
different from the rule for SELECT in WITH: as stated in the
previous section, execution of a SELECT is carried only as far as
the primary query demands its output.

You're apparently expecting the presence of a volatile function to cause the SELECT to be reclassified as data-modifying, but we don't do it that way.

I'd recommend being less cute and just writing

BEGIN;
SELECT pg_advisory_xact_lock(1);
INSERT INTO my_table (...) VALUES (...); COMMIT;

regards, tom lane

[1] https://www.postgresql.org/docs/current/queries-with.html#QUERIES-WITH-CYCLE

[2] https://www.postgresql.org/docs/current/queries-with.html#QUERIES-WITH-MODIFYING

In response to

Browse pgsql-bugs by date

  From Date Subject
Next Message PG Bug reporting form 2025-10-03 10:11:17 BUG #19071: commit b448f1c8d broke LEFT JOIN pushdown
Previous Message John Naylor 2025-10-03 09:28:54 Re: [Bug] Usage of stale dead_items pointer in parallel vacuum