ON CONFLICT DO SELECT (take 3)

Поиск
Список
Период
Сортировка
Искать

ON CONFLICT DO SELECT (take 3)

От:
Viktor Holmberg <v@viktorh.net>
Дата:
Вложения:
Hi!

This patch implements ON CONFLICT DO SELECT. 
This feature would be very handy in bunch of cases, for example idempotent APIs.
I’ve worked around the lack of this by using three statements, like: SELECT -> INSERT if not found -> SELECT again for concurrency safety. (And having to do that dance is driving me nuts)

Apart from the convenience, it’ll also have a performance boost in cases with high latency.

As evidence of that fact that this is needed, and workarounds are complicated, see this stack overflow question: https://stackoverflow.com/questions/16123944/write-a-postgres-get-or-create-sql-query or this entire podcast episode (!) https://www.youtube.com/watch?v=59CainMBjtQ

This patch is 85% the work of Andreas Karlsson and the reviewers (Dean Rasheed, Joel Jacobson, Kirill Reshke) in this thread: https://www.postgresql.org/message-id/flat/2b5db2e6-8ece-44d0-9890-f256fdca9f7e%40proxel.se, which unfortunately seems to have stalled.
I’ve fixed up all the issues mentioned in that thread (at least I think so), plus some minor extra stuff:
  1. Made it work with partitioned tables
  2. Added isolation test
  3. Added tests for row-level security
  4. Added tests for partitioning
  5. Docs updated
  6. Comment misspellings fixed
  7. Renamed struct OnConflictSetState -> OnConflictActionState
I’ve kept the patches proposed there separate, in case any of the people involved back then would like to pick it up again.

Grateful in advance to anyone who can help reviewing!

/Viktor

Re: ON CONFLICT DO SELECT (take 3)

От:
Dean Rasheed <dean.a.rasheed@gmail.com>
Дата:
Вложения:
On Tue, 7 Oct 2025 at 12:57, Viktor Holmberg  wrote:
>
> This patch implements ON CONFLICT DO SELECT.
> I’ve kept the patches proposed there separate, in case any of the people involved back then would like to pick it up again.
>
> Grateful in advance to anyone who can help reviewing!

Thanks for picking this up. I haven't looked at it yet, but I'm
planning to do so.

In the meantime, I noticed that the cfbot didn't pick up your latest
patches, and is still running the v7 patches, presumably based on
their names. So here they are as v8 (rebased, plus a couple of
indentation fixes in 0003, but no other changes).

Regards,
Dean

Re: ON CONFLICT DO SELECT (take 3)

От:
Viktor Holmberg <v@viktorh.net>
Дата:
Ah, must’ve been that I added the previous thread for referene on the commitfest entry. Thanks for sorting that out.
Looking forward to your review!

/Viktor
On 10 Nov 2025 at 10:21 +0100, Dean Rasheed <dean.a.rasheed@gmail.com>, wrote:
On Tue, 7 Oct 2025 at 12:57, Viktor Holmberg <v@viktorh.net> wrote:

This patch implements ON CONFLICT DO SELECT.
I’ve kept the patches proposed there separate, in case any of the people involved back then would like to pick it up again.

Grateful in advance to anyone who can help reviewing!

Thanks for picking this up. I haven't looked at it yet, but I'm
planning to do so.

In the meantime, I noticed that the cfbot didn't pick up your latest
patches, and is still running the v7 patches, presumably based on
their names. So here they are as v8 (rebased, plus a couple of
indentation fixes in 0003, but no other changes).

Regards,
Dean

Re: ON CONFLICT DO SELECT (take 3)

От:
Viktor Holmberg <v@viktorh.net>
Дата:
Вложения:
Here are some updates that needed to be done after the improvements to the RLS docs / tests in 7dc4fa & 2e8424.

On 10 Nov 2025, at 11:18, Viktor Holmberg <v@viktorh.net> wrote:

Ah, must’ve been that I added the previous thread for referene on the commitfest entry. Thanks for sorting that out.
Looking forward to your review!

/Viktor
On 10 Nov 2025 at 10:21 +0100, Dean Rasheed <dean.a.rasheed@gmail.com>, wrote:
On Tue, 7 Oct 2025 at 12:57, Viktor Holmberg <v@viktorh.net> wrote:

This patch implements ON CONFLICT DO SELECT.
I’ve kept the patches proposed there separate, in case any of the people involved back then would like to pick it up again.

Grateful in advance to anyone who can help reviewing!

Thanks for picking this up. I haven't looked at it yet, but I'm
planning to do so.

In the meantime, I noticed that the cfbot didn't pick up your latest
patches, and is still running the v7 patches, presumably based on
their names. So here they are as v8 (rebased, plus a couple of
indentation fixes in 0003, but no other changes).

Regards,
Dean

Re: ON CONFLICT DO SELECT (take 3)

От:
jian he <jian.universality@gmail.com>
Дата:
On Fri, Nov 14, 2025 at 10:34 PM Viktor Holmberg  wrote:
>
> Here are some updates that needed to be done after the improvements to the RLS docs / tests in 7dc4fa & 2e8424.
>
hi.

I see this:
https://commitfest.postgresql.org/patch/6109/
already mentioned all the related discussion links.

Could you also include the discussion link in the commit message?
currently this
spread across several email threads, adding the link would help others
understand the context.

----------------------------
create table x(key int4, fruit text);
create unique index x_idx on x(key);
create role alice;
grant all on schema public to alice;
grant insert on x to alice;
grant select(key) on x to alice;
set role alice;
explain (costs off, verbose) insert into x as i values (1, 'Apple') on
conflict (key) do select where i.fruit = 'Apple' returning 1;
explain (costs off, verbose) insert into x as i values (1, 'Apple') on
conflict (key) do select returning 1;

The above simple tests seem to show ON CONFLICT DO SELECT
permission working as intended, (I didn't try harder this time).

It looks like we currently lack permission-related regression tests
(no ``ERROR:  permission denied for``),
we obviously need more.


--
jian
https://www.enterprisedb.com/


Re: ON CONFLICT DO SELECT (take 3)

От:
jian he <jian.universality@gmail.com>
Дата:
On Sat, Nov 15, 2025 at 5:24 AM jian he  wrote:
>
> On Fri, Nov 14, 2025 at 10:34 PM Viktor Holmberg  wrote:
> >
> > Here are some updates that needed to be done after the improvements to the RLS docs / tests in 7dc4fa & 2e8424.
> >

hi.

I did some simple tests, found out that
SELECT FOR UPDATE, the lock mechanism seems to be working as intended.
We can add some tests on contrib/pgrowlocks to demonstrate that.


infer_arbiter_indexes
                ereport(ERROR,
                        (errcode(ERRCODE_WRONG_OBJECT_TYPE),
                         errmsg("ON CONFLICT DO UPDATE not supported
with exclusion constraints")));
I guess this works for ON CONFLICT SELECT?
we can leave some comments on the function infer_arbiter_indexes,
and also add some tests on src/test/regress/sql/constraints.sql after line 570.


changing
OnConflictSetState
to
OnConflictActionState
could make it a separate patch.

all these 3 patches can be merged together, I think.
----------------------------------------
typedef struct OnConflictExpr
{
    NodeTag        type;
    OnConflictAction action;    /* DO NOTHING or UPDATE? */

"/* DO NOTHING or UPDATE? */"
this comment needs to be changed?
----------------------------------------
src/backend/rewrite/rewriteHandler.c
parsetree->onConflict->action == ONCONFLICT_UPDATE
maybe we also need to do some logic to the ONCONFLICT_SELECT
(I didn't check this part deeply)

src/test/regress/sql/updatable_views.sql, there are many occurence of
"on conflict".
I think we also need tests for ON CONFLICT DO SELECT.

CREATE TABLE base_tbl (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
INSERT INTO base_tbl SELECT i, 'Row ' || i FROM generate_series(-2, 2) g(i);
CREATE VIEW rw_view15 AS SELECT a, upper(b) FROM base_tbl;
INSERT INTO rw_view15 (a) VALUES (3);
truncate base_tbl;
INSERT INTO rw_view15 (a) VALUES (3);
INSERT INTO rw_view15 (a) VALUES (3) ON CONFLICT (a) DO SELECT WHERE
excluded.upper = 'UNSPECIFIED' RETURNING *;
INSERT INTO rw_view15 (a) VALUES (3) ON CONFLICT (a) DO UPDATE SET a =
excluded.a WHERE excluded.upper = 'UNSPECIFIED' RETURNING *;
INSERT INTO rw_view15 (a) VALUES (3) ON CONFLICT (a) DO SELECT WHERE
excluded.upper = 'Unspecified' RETURNING *;
INSERT INTO rw_view15 (a) VALUES (3) ON CONFLICT (a) DO UPDATE SET a =
excluded.a WHERE excluded.upper = 'Unspecified' RETURNING *;

If you compare it with the result above, it seems the updatable view behaves
inconsistent with ON CONFLICT DO SELECT versus ON CONFLICT DO UPDATE.

--
jian
https://www.enterprisedb.com/


Re: ON CONFLICT DO SELECT (take 3)

От:
"v@viktorh.net" <v@viktorh.net>
Дата:
Thanks for the review Jian. Much appreciated. Apologies for the multiple email threads - just my email client mucking up the threads. This should hopefully bring them back to the mail thread.
I’ll go over it and make changes this week.
One question - why break out the OnConflictSet/ActionState rename to a separate commit? Previously, it only did Set (in update) so it’s naming did make sense.

> On 15 Nov 2025, at 12:11, jian he  wrote:
> 
> On Sat, Nov 15, 2025 at 5:24 AM jian he  wrote:
>> 
>> On Fri, Nov 14, 2025 at 10:34 PM Viktor Holmberg  wrote:
>>> 
>>> Here are some updates that needed to be done after the improvements to the RLS docs / tests in 7dc4fa & 2e8424.
>>> 
> 
> hi.
> 
> I did some simple tests, found out that
> SELECT FOR UPDATE, the lock mechanism seems to be working as intended.
> We can add some tests on contrib/pgrowlocks to demonstrate that.
> 
> 
> infer_arbiter_indexes
>                ereport(ERROR,
>                        (errcode(ERRCODE_WRONG_OBJECT_TYPE),
>                         errmsg("ON CONFLICT DO UPDATE not supported
> with exclusion constraints")));
> I guess this works for ON CONFLICT SELECT?
> we can leave some comments on the function infer_arbiter_indexes,
> and also add some tests on src/test/regress/sql/constraints.sql after line 570.
> 
> 
> changing
> OnConflictSetState
> to
> OnConflictActionState
> could make it a separate patch.
> 
> all these 3 patches can be merged together, I think.
> ----------------------------------------
> typedef struct OnConflictExpr
> {
>    NodeTag        type;
>    OnConflictAction action;    /* DO NOTHING or UPDATE? */
> 
> "/* DO NOTHING or UPDATE? */"
> this comment needs to be changed?
> ----------------------------------------
> src/backend/rewrite/rewriteHandler.c
> parsetree->onConflict->action == ONCONFLICT_UPDATE
> maybe we also need to do some logic to the ONCONFLICT_SELECT
> (I didn't check this part deeply)
> 
> src/test/regress/sql/updatable_views.sql, there are many occurence of
> "on conflict".
> I think we also need tests for ON CONFLICT DO SELECT.
> 
> CREATE TABLE base_tbl (a int PRIMARY KEY, b text DEFAULT 'Unspecified');
> INSERT INTO base_tbl SELECT i, 'Row ' || i FROM generate_series(-2, 2) g(i);
> CREATE VIEW rw_view15 AS SELECT a, upper(b) FROM base_tbl;
> INSERT INTO rw_view15 (a) VALUES (3);
> truncate base_tbl;
> INSERT INTO rw_view15 (a) VALUES (3);
> INSERT INTO rw_view15 (a) VALUES (3) ON CONFLICT (a) DO SELECT WHERE
> excluded.upper = 'UNSPECIFIED' RETURNING *;
> INSERT INTO rw_view15 (a) VALUES (3) ON CONFLICT (a) DO UPDATE SET a =
> excluded.a WHERE excluded.upper = 'UNSPECIFIED' RETURNING *;
> INSERT INTO rw_view15 (a) VALUES (3) ON CONFLICT (a) DO SELECT WHERE
> excluded.upper = 'Unspecified' RETURNING *;
> INSERT INTO rw_view15 (a) VALUES (3) ON CONFLICT (a) DO UPDATE SET a =
> excluded.a WHERE excluded.upper = 'Unspecified' RETURNING *;
> 
> If you compare it with the result above, it seems the updatable view behaves
> inconsistent with ON CONFLICT DO SELECT versus ON CONFLICT DO UPDATE.
> 
> --
> jian
> https://www.enterprisedb.com/

> On 10 Nov 2025, at 11:18, Viktor Holmberg  wrote:
> 
> Ah, must’ve been that I added the previous thread for referene on the commitfest entry. Thanks for sorting that out.
> Looking forward to your review!
> 
> /Viktor
> On 10 Nov 2025 at 10:21 +0100, Dean Rasheed , wrote:
>> On Tue, 7 Oct 2025 at 12:57, Viktor Holmberg  wrote:
>>> 
>>> This patch implements ON CONFLICT DO SELECT.
>>> I’ve kept the patches proposed there separate, in case any of the people involved back then would like to pick it up again.
>>> 
>>> Grateful in advance to anyone who can help reviewing!
>> 
>> Thanks for picking this up. I haven't looked at it yet, but I'm
>> planning to do so.
>> 
>> In the meantime, I noticed that the cfbot didn't pick up your latest
>> patches, and is still running the v7 patches, presumably based on
>> their names. So here they are as v8 (rebased, plus a couple of
>> indentation fixes in 0003, but no other changes).
>> 
>> Regards,
>> Dean



Re: ON CONFLICT DO SELECT (take 3)

От:
Dean Rasheed <dean.a.rasheed@gmail.com>
Дата:
On Mon, 17 Nov 2025 at 10:00, v@viktorh.net  wrote:
>
> One question - why break out the OnConflictSet/ActionState rename to a separate commit? Previously, it only did Set (in update) so it’s naming did make sense.
>

I know that some committers tend to prefer smaller commits than me,
but FWIW, I wouldn't bother splitting out something like this, since
it doesn't really provide any benefit by itself, or really make much
sense without the rest of the patch.

P.S. The convention on these mailing lists is to not top-post, but
instead reply in-line and trim, like this.

Regards,
Dean


Re: ON CONFLICT DO SELECT (take 3)

От:
"v@viktorh.net" <v@viktorh.net>
Дата:
Вложения:

>> I did some simple tests, found out that
>> SELECT FOR UPDATE, the lock mechanism seems to be working as intended.
>> We can add some tests on contrib/pgrowlocks to demonstrate that.
Test added.

>> infer_arbiter_indexes
>>               ereport(ERROR,
>>                       (errcode(ERRCODE_WRONG_OBJECT_TYPE),
>>                        errmsg("ON CONFLICT DO UPDATE not supported
>> with exclusion constraints")));
>> I guess this works for ON CONFLICT SELECT?
>> we can leave some comments on the function infer_arbiter_indexes,
>> and also add some tests on src/test/regress/sql/constraints.sql after line 570.
Good catch. In fact it did “work” as in "not crash" - but I think it shouldn’t.
With exclusion constraints, a single insert can conflict with multiple rows. 
I assumed that’s why DO UPDATE doesn’t work with it - because it’d update multiple rows.
For the same reason, I think DO SELECT shouldn’t work either, as you could then 
get multiple rows back for a single insert.
I guess in both cases you could make it so it updates/selects all conflicting rows - but I’d 
really prefer to leave it as an error. If someone actually wants this to work with exclusion
constraints the error can always be removed in a future version. But if we add a multi-row-return
then we are locked in forever.

>> changing
>> OnConflictSetState
>> to
>> OnConflictActionState
>> could make it a separate patch.
Skipping this for now, let me know if you strongly object.

>> all these 3 patches can be merged together, I think.
Ok done. But these review fixes are separate for ease of review. Before merging they should
be folded in to the main/first commit.

>> "/* DO NOTHING or UPDATE? */"
>> this comment needs to be changed?
Done

>> ----------------------------------------
>> src/backend/rewrite/rewriteHandler.c
>> parsetree->onConflict->action == ONCONFLICT_UPDATE
>> maybe we also need to do some logic to the ONCONFLICT_SELECT
>> (I didn't check this part deeply)
Yes, this needed to be fixed to make updatable views work. Done.
>> If you compare it with the result above, it seems the updatable view behaves
>> inconsistent with ON CONFLICT DO SELECT versus ON CONFLICT DO UPDATE.
Yes, it was wrong. Nice catch. Fixed now I think, and test added.


I believe this new patch addresses all the issues found by Jian. I hope another review won’t find quite so much dirt!

Re: ON CONFLICT DO SELECT (take 3)

От:
Dean Rasheed <dean.a.rasheed@gmail.com>
Дата:
Вложения:
On Mon, 17 Nov 2025 at 22:07, v@viktorh.net  wrote:
>
> I believe this new patch addresses all the issues found by Jian. I hope another review won’t find quite so much dirt!
>

The latest set of changes look reasonable to me, so I've squashed
those 2 commits together and made an initial stab at writing a more
complete commit message.

I made a quick pass over the code, and I'm attaching a few more
suggested updates. This is mostly cosmetic stuff (e.g., fixing a few
code comments that were overlooked), plus some minor refactoring to
reduce code duplication.

Regards,
Dean

Re: ON CONFLICT DO SELECT (take 3)

От:
Viktor Holmberg <v@viktorh.net>
Дата:
On 19 Nov 2025 at 15:08 +0100, Dean Rasheed <dean.a.rasheed@gmail.com>, wrote:
I made a quick pass over the code, and I'm attaching a few more
suggested updates. This is mostly cosmetic stuff (e.g., fixing a few
code comments that were overlooked), plus some minor refactoring to
reduce code duplication.
Neat!
For the CASE default, elog(ERROR, "unrecognized LockClauseStrength %d” that was removed.
Would this now trigger a compile time error/warning? And are you supposed to get 0 warnings when compiling? 
(I get a large amount of warnings "warning: 'pg_restrict' macro redefined" on master, but that could just be something with my environment)
More of a question, the changes are an improvement.

/Viktor

Re: ON CONFLICT DO SELECT (take 3)

От:
Dean Rasheed <dean.a.rasheed@gmail.com>
Дата:
On Wed, 19 Nov 2025 at 16:51, Viktor Holmberg  wrote:
>
> For the CASE default, elog(ERROR, "unrecognized LockClauseStrength %d” that was removed.
> Would this now trigger a compile time error/warning? And are you supposed to get 0 warnings when compiling?

That shouldn't trigger a warning, because there is a case block for
every enum element, and yes there should be 0 compiler warnings.

> (I get a large amount of warnings "warning: 'pg_restrict' macro redefined" on master, but that could just be something with my environment)

I haven't seen that before, but there's this thread:

https://www.postgresql.org/message-id/flat/CA%2BFpmFdoa7O7yS3k7ZtqvA%2BhNWUA6YvJy6VvdYX1sGsryVQBNQ%40mail.gmail.com

If you re-run configure, does it go away?

Regards,
Dean


Re: ON CONFLICT DO SELECT (take 3)

От:
Marko Tiikkaja <marko@joh.to>
Дата:
On Tue, Oct 7, 2025 at 2:57 PM Viktor Holmberg  wrote:
> This patch is 85% the work of Andreas Karlsson and the reviewers (Dean Rasheed, Joel Jacobson, Kirill Reshke) in this thread: https://www.postgresql.org/message-id/flat/2b5db2e6-8ece-44d0-9890-f256fdca9f7e%40proxel.se, which unfortunately seems to have stalled.

This was also based on my work, and according to Andreas the first
version was "very similar" to mine.


.m


Re: ON CONFLICT DO SELECT (take 3)

От:
Viktor Holmberg <v@viktorh.net>
Дата:
On 19 Nov 2025 at 18:19 +0100, Dean Rasheed <dean.a.rasheed@gmail.com>, wrote:
On Wed, 19 Nov 2025 at 16:51, Viktor Holmberg <v@viktorh.net> wrote:

For the CASE default, elog(ERROR, "unrecognized LockClauseStrength %d” that was removed.
Would this now trigger a compile time error/warning? And are you supposed to get 0 warnings when compiling?
That shouldn't trigger a warning, because there is a case block for
every enum element, and yes there should be 0 compiler warnings.
Yes sorry, that’s what I meant! In that case, nice that those potential future errors are moved from runtime to compile time.
(I get a large amount of warnings "warning: 'pg_restrict' macro redefined" on master, but that could just be something with my environment)
I haven't seen that before, but there's this thread:

https://www.postgresql.org/message-id/flat/CA%2BFpmFdoa7O7yS3k7ZtqvA%2BhNWUA6YvJy6VvdYX1sGsryVQBNQ%40mail.gmail.com

If you re-run configure, does it go away?

Regards,
Dean
Yes, re-configuring made the warning go away. Thanks for pointing me in the right direction.

Re: ON CONFLICT DO SELECT (take 3)

От:
Andreas Karlsson <andreas@proxel.se>
Дата:
On 11/19/25 8:06 PM, Marko Tiikkaja wrote:
> On Tue, Oct 7, 2025 at 2:57 PM Viktor Holmberg  wrote:
>> This patch is 85% the work of Andreas Karlsson and the reviewers (Dean Rasheed, Joel Jacobson, Kirill Reshke) in this thread: https://www.postgresql.org/message-id/flat/2b5db2e6-8ece-44d0-9890-f256fdca9f7e%40proxel.se, which unfortunately seems to have stalled.
> 
> This was also based on my work, and according to Andreas the first
> version was "very similar" to mine.

Yup! "My" patch was just Marko's patch rebased on PG17/PG18 and with 
support for new PG features added, more tests and a couple of bugs 
fixed. The original idea and huge parts of the patch are indeed Marko's.

I hope I never gave the impression otherwise. :)

Andreas


Re: ON CONFLICT DO SELECT (take 3)

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
On Wed, Nov 19, 2025 at 10:08 PM Dean Rasheed  wrote:
>
> The latest set of changes look reasonable to me, so I've squashed
> those 2 commits together and made an initial stab at writing a more
> complete commit message.
>

hi.

"Note that exclusion constraints are not supported as arbiters with ON
CONFLICT DO UPDATE."
this sentence need update?


"""
If the INSERT command contains a RETURNING clause, the result will be similar to
that of a SELECT statement containing the columns and values defined in the
RETURNING list, computed over the row(s) inserted or updated by the command.
"""
this sentence need update?


 HINT:  Perhaps you meant to reference the column "excluded.fruit".
 -- inference fails:
-insert into insertconflicttest values (3, 'Kiwi') on conflict (key,
fruit) do update set fruit = excluded.fruit;
+insert into insertconflicttest values (4, 'Kiwi') on conflict (key,
fruit) do update set fruit = excluded.fruit;
 ERROR:  there is no unique or exclusion constraint matching the ON
CONFLICT specification
-insert into insertconflicttest values (4, 'Mango') on conflict
(fruit, key) do update set fruit = excluded.fruit;
+insert into insertconflicttest values (5, 'Mango') on conflict
(fruit, key) do update set fruit = excluded.fruit;
 ERROR:  there is no unique or exclusion constraint matching the ON
CONFLICT specification
-insert into insertconflicttest values (5, 'Lemon') on conflict
(fruit) do update set fruit = excluded.fruit;
+insert into insertconflicttest values (6, 'Lemon') on conflict
(fruit) do update set fruit = excluded.fruit;
 ERROR:  there is no unique or exclusion constraint matching the ON
CONFLICT specification
-insert into insertconflicttest values (6, 'Passionfruit') on conflict
(lower(fruit)) do update set fruit = excluded.fruit;
+insert into insertconflicttest values (7, 'Passionfruit') on conflict
(lower(fruit)) do update set fruit = excluded.fruit;

all these changes is not necessary, we can just add
+truncate insertconflicttest;
+insert into insertconflicttest values (1, 'Apple'), (2, 'Orange');
after line
explain (costs off) insert into insertconflicttest values (1, 'Apple')
on conflict (key) do select for key share returning *;
to make table insertconflicttest have the same content as before ON
CONFLICT DO SELECT.


it seems we didn't test ExecInitPartitionInfo related changes,
I've attached a simple test for it.


https://www.postgresql.org/docs/current/ddl-priv.html#DDL-PRIV-UPDATE
says:
```
SELECT ... FOR UPDATE and SELECT ... FOR SHARE also require this privilege on at
least one column, in addition to the SELECT privilege.
```
I attached extensive permission tests for ON CONFLICT DO SELECT


in ExecOnConflictSelect, i change it to:
```
        if (!table_tuple_fetch_row_version(relation, conflictTid,
SnapshotAny, existing))
        {
            elog(INFO, "this part reached");
            return false;
        }
```
all isolation tests passed, this seems unlikely to be reachable.


--
jian
https://www.enterprisedb.com/

Re: ON CONFLICT DO SELECT (take 3)

От:
Dean Rasheed <dean.a.rasheed@gmail.com>
Дата:
On 11/19/25 8:06 PM, Marko Tiikkaja wrote:
> On Tue, Oct 7, 2025 at 2:57 PM Viktor Holmberg  wrote:
>> This patch is 85% the work of Andreas Karlsson and the reviewers (Dean Rasheed, Joel Jacobson, Kirill Reshke) in this thread: https://www.postgresql.org/message-id/flat/2b5db2e6-8ece-44d0-9890-f256fdca9f7e%40proxel.se, which unfortunately seems to have stalled.
>
> This was also based on my work, and according to Andreas the first
> version was "very similar" to mine.

Ah, sorry about that. I didn't go back through the old threads carefully enough.

On Thu, 20 Nov 2025 at 01:29, Andreas Karlsson  wrote:
>
> Yup! "My" patch was just Marko's patch rebased on PG17/PG18 and with
> support for new PG features added, more tests and a couple of bugs
> fixed. The original idea and huge parts of the patch are indeed Marko's.

OK, got it. So author credit for this patch should go to Marko,
Andreas, and Viktor? In that order? And I should add the original
thread to the commit message.

Regards,
Dean


Re: ON CONFLICT DO SELECT (take 3)

От:
Marko Tiikkaja <marko@joh.to>
Дата:
On Thu, Nov 20, 2025 at 10:50 AM Dean Rasheed  wrote:
> On Thu, 20 Nov 2025 at 01:29, Andreas Karlsson  wrote:
> >
> > Yup! "My" patch was just Marko's patch rebased on PG17/PG18 and with
> > support for new PG features added, more tests and a couple of bugs
> > fixed. The original idea and huge parts of the patch are indeed Marko's.
>
> OK, got it. So author credit for this patch should go to Marko,
> Andreas, and Viktor? In that order? And I should add the original
> thread to the commit message.

I think Andreas gets first author on this one.

Thanks!


.m


Re: ON CONFLICT DO SELECT (take 3)

От:
Viktor Holmberg <v@viktorh.net>
Дата:
On 20 Nov 2025 at 09:50 +0100, Marko Tiikkaja <marko@joh.to>, wrote:
On Thu, Nov 20, 2025 at 10:50 AM Dean Rasheed <dean.a.rasheed@gmail.com> wrote:
On Thu, 20 Nov 2025 at 01:29, Andreas Karlsson <andreas@proxel.se> wrote:

Yup! "My" patch was just Marko's patch rebased on PG17/PG18 and with
support for new PG features added, more tests and a couple of bugs
fixed. The original idea and huge parts of the patch are indeed Marko's.

OK, got it. So author credit for this patch should go to Marko,
Andreas, and Viktor? In that order? And I should add the original
thread to the commit message.

I think Andreas gets first author on this one.

Thanks!

.m
I don’t mind the author credit order, I just want to delete the 
SELECT INSERT SELECT dances from my code. (in 2 years or
 however long it will take for PG19 to trickle down to heroku).
So all fine by me!
/Viktor

Re: ON CONFLICT DO SELECT (take 3)

От:
jian he <jian.universality@gmail.com>
Дата:
>
>
> https://www.postgresql.org/docs/current/ddl-priv.html#DDL-PRIV-UPDATE
> says:
> ```
> SELECT ... FOR UPDATE and SELECT ... FOR SHARE also require this privilege on at
> least one column, in addition to the SELECT privilege.
> ```
> I attached extensive permission tests for ON CONFLICT DO SELECT
>
>

+   For ON CONFLICT DO SELECT, SELECT
+   privilege is required on any column whose values are read in the
+   condition.
If you do ON CONFLICT DO SELECT FOR UPDATE
then UPDATE permission is also required  (at least
one column),
can we also mention this?


+ /* Parse analysis should already have disallowed this */
+ Assert(resultRelInfo->ri_projectReturning);
+
+ /* Process RETURNING like an UPDATE that didn't change anything */
+ *rslot = ExecProcessReturning(context, resultRelInfo, CMD_UPDATE,
+  existing, existing, context->planSlot);

The above two comments seem confusing. If you look at the code
ExecProcessReturning, I think you can set the cmdType as CMD_INSERT.

+ if (lockstrength != LCS_NONE)
+ {
+ LockTupleMode lockmode;
+
+ switch (lockstrength)
+ {
+ case LCS_FORKEYSHARE:
+ lockmode = LockTupleKeyShare;
+ break;
+ case LCS_FORSHARE:
+ lockmode = LockTupleShare;
+ break;
+ case LCS_FORNOKEYUPDATE:
+ lockmode = LockTupleNoKeyExclusive;
+ break;
+ case LCS_FORUPDATE:
+ lockmode = LockTupleExclusive;
+ break;
+ default:
+ elog(ERROR, "unexpected lock strength %d", lockstrength);
+ }
+
+ if (!ExecOnConflictLockRow(context, existing, conflictTid,
+   resultRelInfo->ri_RelationDesc, lockmode, false))
+ return false;

isolation tests do not test the case where ExecOnConflictLockRow returns false.
actually it's reachable.

-----------------------------setup---------------------
drop table if exists tsa1;
create table tsa1(a int, b int, constraint xxidx unique (a));
insert into tsa1 values (1,2);

session1, using GDB set a breakpoint at ExecOnConflictLockRow.
session1:
              insert into tsa1 values(1,3) on conflict(a) do select
for update returning *;
session2:
             update tsa1 set a = 111;

session1:     session 1 already reached the GDB breakpoint
(ExecOnConflictLockRow), issue
``continue`` in GDB let session1 complete.
----------------------------------------------------------------------------
I'm wondering how we can add test coverage for this.


+      
+       ON CONFLICT DO SELECT FOR UPDATE/SHARE
+       Check existing rows
+       —
+       Existing row
+       —
+       —
       

Here, it should be "
Check existing row
"?

If you search 'ON CONFLICT', it appears on many sgml files, currently we only
made change to:
doc/src/sgml/dml.sgml
doc/src/sgml/ref/create_policy.sgml
doc/src/sgml/ref/insert.sgml

seems other sgml files also need to be updated.


--
jian
https://www.enterprisedb.com/


Re: ON CONFLICT DO SELECT (take 3)

От:
Andreas Karlsson <andreas@proxel.se>
Дата:
On 11/20/25 9:49 AM, Dean Rasheed wrote:
> OK, got it. So author credit for this patch should go to Marko,
> Andreas, and Viktor? In that order? And I should add the original
> thread to the commit message.

Sounds good!

Andreas


Re: ON CONFLICT DO SELECT (take 3)

От:
Viktor Holmberg <v@viktorh.net>
Дата:
Вложения:
On 20 Nov 2025 at 16:27 +0100, jian he <jian.universality@gmail.com>, wrote:
https://www.postgresql.org/docs/current/ddl-priv.html#DDL-PRIV-UPDATE
says:
```
SELECT ... FOR UPDATE and SELECT ... FOR SHARE also require this privilege on at
least one column, in addition to the SELECT privilege.
```
I attached extensive permission tests for ON CONFLICT DO SELECT

I’ve added in both the tests you sent over as is Jian. I was sure I wrote some tests for the partitioning, but I must’ve forgot to commit them, so thanks for that.

+ For <literal>ON CONFLICT DO SELECT</literal>, <literal>SELECT</literal>
+ privilege is required on any column whose values are read in the
+ <replaceable>condition</replaceable>.
If you do <literal>ON CONFLICT DO SELECT FOR UPDATE</literal>
then <literal>UPDATE</literal> permission is also required (at least
one column),
can we also mention this?

I’ve update the docs in all the cases you mentioned. I’ve also grepped through the docs for “ON CONFLICT” and “DO UPDATE” and fixed upp all mentions where it made sense

+ /* Parse analysis should already have disallowed this */
+ Assert(resultRelInfo->ri_projectReturning);
+
+ /* Process RETURNING like an UPDATE that didn't change anything */
+ *rslot = ExecProcessReturning(context, resultRelInfo, CMD_UPDATE,
+ existing, existing, context->planSlot);

The above two comments seem confusing. If you look at the code
ExecProcessReturning, I think you can set the cmdType as CMD_INSERT.

Yes. I’ve clarified the comments too. Kinda itching to rewrite ExecProcessReturning so that you pass in defaultTuple(OLD, NEW) as a boolean or something - as that is all CMD_TYPE does. But in the interest of getting this committed, I’m refraining from that

+ if (!ExecOnConflictLockRow(context, existing, conflictTid,
+ resultRelInfo->ri_RelationDesc, lockmode, false))
+ return false;

isolation tests do not test the case where ExecOnConflictLockRow returns false.
actually it's reachable.

-----------------------------setup---------------------
drop table if exists tsa1;
create table tsa1(a int, b int, constraint xxidx unique (a));
insert into tsa1 values (1,2);

session1, using GDB set a breakpoint at ExecOnConflictLockRow.
session1:
insert into tsa1 values(1,3) on conflict(a) do select
for update returning *;
session2:
update tsa1 set a = 111;

session1: session 1 already reached the GDB breakpoint
(ExecOnConflictLockRow), issue
``continue`` in GDB let session1 complete.
----------------------------------------------------------------------------
I'm wondering how we can add test coverage for this.

I’ve done some minor refactoring to this code, and added some comments.
Regarding testing for it - I agree it’d be nice to have, but I have no idea how one would go about that.
Considering you tested it and the behaviour is correct, I’m hoping that we don’t consider this a blocker

Thanks for the thorough review Jian!

Re: ON CONFLICT DO SELECT (take 3)

От:
Viktor Holmberg <v@viktorh.net>
Дата:
Вложения:
Got a complication warning in CI: error: ‘lockmode’ may be used uninitialized. Hopefully this fixes it.

Re: ON CONFLICT DO SELECT (take 3)

От:
Viktor Holmberg <v@viktorh.net>
Дата:
Вложения:
On 24 Nov 2025 at 11:39 +0100, Viktor Holmberg <v@viktorh.net>, wrote:
Got a complication warning in CI: error: ‘lockmode’ may be used uninitialized. Hopefully this fixes it.
It did not. But this will.
For some reason, in this bit:

‘''
LockTupleMode lockmode;
….
case LCS_FORUPDATE:
 lockmode = LockTupleExclusive;
 break;
 case LCS_NONE:
 elog(ERROR, "unexpected lock strength %d", lockStrength);
 }

 if (!ExecOnConflictLockRow(context, existing, conflictTid,
 resultRelInfo->ri_RelationDesc, lockmode, false))
 return false;
‘''

GCC gives warning "error: ‘lockmode’ may be used uninitialized”. But if I switch the final exhaustive “case" to a “default” the warning goes away. Strange, if anyone know how to fix let me know. But also I don’t think it’s a big deal.

Re: ON CONFLICT DO SELECT (take 3)

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
On Mon, Nov 24, 2025 at 11:23 PM Viktor Holmberg  wrote:
>
> It did not. But this will.
> For some reason, in this bit:
>
> ‘''
> LockTupleMode lockmode;
> ….
> case LCS_FORUPDATE:
>  lockmode = LockTupleExclusive;
>  break;
>  case LCS_NONE:
>  elog(ERROR, "unexpected lock strength %d", lockStrength);
>  }
>
>  if (!ExecOnConflictLockRow(context, existing, conflictTid,
>  resultRelInfo->ri_RelationDesc, lockmode, false))
>  return false;
> ‘''
>
> GCC gives warning "error: ‘lockmode’ may be used uninitialized”. But if I switch the final exhaustive “case" to a “default” the warning goes away. Strange, if anyone know how to fix let me know. But also I don’t think it’s a big deal.

hi.
you can search ``/* keep compiler quiet */`` within the codebase.

after
``elog(ERROR, "unexpected lock strength %d", lockStrength);``
you can add
``
lockmode = LockTupleExclusive;
break;
``

in doc/src/sgml/mvcc.sgml:
   
    INSERT with an ON CONFLICT DO
    NOTHING clause may have insertion not proceed for a row due to
    the outcome of another transaction whose effects are not visible
    to the INSERT snapshot.  Again, this is only
    the case in Read Committed mode.
   
I think we need to add something after the above quoted paragraph.

doc/src/sgml/ref/create_view.sgml, some places also need to be updated, I think.
see text ON CONFLICT UPDATE in there.

I added some dummy tests on src/test/regress/sql/triggers.sql.
also did some minor doc changes.

please check the attached v16.
v16-0001: rebase and combine v15-0001, v15-0002, v15-0003, v15-0004 together.
v16-0002: using INJECTION_POINT to test the case when
ExecOnConflictSelect->ExecOnConflictLockRow returns false.

v16-0002, I use
```
        if (!ExecOnConflictLockRow(context, existing, conflictTid,
                                   resultRelInfo->ri_RelationDesc,
lockmode, false))
        {
            INJECTION_POINT("exec-onconflictselect-after-lockrow", NULL);
            elog(INFO, "this part is reached");
            return false;
        }
```
to demomate that ExecOnConflictLockRow is reachable.
obviously, ``elog(INFO, "this part is reached");`` needs to be removed later.


--
jian
https://www.enterprisedb.com/

Re: ON CONFLICT DO SELECT (take 3)

От:
Dean Rasheed <dean.a.rasheed@gmail.com>
Дата:
On Tue, 25 Nov 2025 at 08:33, jian he  wrote:
>
> v16-0002: using INJECTION_POINT to test the case when
> ExecOnConflictSelect->ExecOnConflictLockRow returns false.
>

In general, having more tests is a good thing, but I think this is
setting a higher bar for the ON CONFLICT DO SELECT than existing code,
such as ON CONFLICT DO UPDATE. ExecOnConflictUpdate() also uses
ExecOnConflictLockRow() in the same way, and doesn't have such a test,
and there are other lock-and-retry paths in the executor not tested in
this way.

IMO, using injection points for testing a wider variety of possible
race conditions in the executor should be considered as a separate
patch.

Regards,
Dean


Re: ON CONFLICT DO SELECT (take 3)

От:
Dean Rasheed <dean.a.rasheed@gmail.com>
Дата:
On Sun, 23 Nov 2025 at 20:34, Viktor Holmberg  wrote:
>
> I’ve update the docs in all the cases you mentioned. I’ve also grepped through the docs for “ON CONFLICT” and “DO UPDATE” and fixed upp all mentions where it made sense
>

--- a/doc/src/sgml/ref/create_table.sgml
+++ b/doc/src/sgml/ref/create_table.sgml
@@ -1380,7 +1380,7 @@ WITH ( MODULUS numeric_literal, REM
       clause.  NOT NULL and
CHECK constraints are not
       deferrable.  Note that deferrable constraints cannot be used as
       conflict arbitrators in an INSERT statement that
-      includes an ON CONFLICT DO UPDATE clause.
+      includes an ON CONFLICT DO UPDATE / SELECT clause.
      
     
    

Actually, a deferrable constraint cannot be used with ON CONFLICT DO
NOTHING either, which makes this a pre-existing documentation bug,
that should be fixed and back-patched separately as follows:

-      includes an ON CONFLICT DO UPDATE clause.
+      includes an ON CONFLICT clause.

In addition, I think we should change the word "arbitrators" to
"arbiters". It means pretty-much the same thing, but the latter is the
term used everywhere else.

I'll take care of that separately, so the above diff won't be needed
in this patch.

Regards,
Dean


Re: ON CONFLICT DO SELECT (take 3)

От:
Viktor Holmberg <v@viktorh.net>
Дата:
Вложения:
On 25 Nov 2025 at 09:33 +0100, jian he <jian.universality@gmail.com>, wrote:
On Mon, Nov 24, 2025 at 11:23 PM Viktor Holmberg <v@viktorh.net> wrote:

It did not. But this will.
For some reason, in this bit:

‘''
LockTupleMode lockmode;
….
case LCS_FORUPDATE:
lockmode = LockTupleExclusive;
break;
case LCS_NONE:
elog(ERROR, "unexpected lock strength %d", lockStrength);
}

if (!ExecOnConflictLockRow(context, existing, conflictTid,
resultRelInfo->ri_RelationDesc, lockmode, false))
return false;
‘''

GCC gives warning "error: ‘lockmode’ may be used uninitialized”. But if I switch the final exhaustive “case" to a “default” the warning goes away. Strange, if anyone know how to fix let me know. But also I don’t think it’s a big deal.

hi.
you can search ``/* keep compiler quiet */`` within the codebase.

after
``elog(ERROR, "unexpected lock strength %d", lockStrength);``
you can add
``
lockmode = LockTupleExclusive;
break;
``
Thanks! I now realise the problem wasn’t that GCC didn’t see that elog wasn’t reachable. It was the fact that there is no default. Even though all cases are covered. This is annoying but switching it back to a default as it was seems the best option. Setting lockmode is not needed if it’s kept as a default. 
My goal was to enumerate all cases so you’d get a compiler warning if one of them wasn’t handled like Dean did, but looks like I’ll have to give up on that until GCC gets improved.

in doc/src/sgml/mvcc.sgml:
<para>
<command>INSERT</command> with an <literal>ON CONFLICT DO
NOTHING</literal> clause may have insertion not proceed for a row due to
the outcome of another transaction whose effects are not visible
to the <command>INSERT</command> snapshot. Again, this is only
the case in Read Committed mode.
</para>
I think we need to add something after the above quoted paragraph.
I’ve added a bit about DO SELECT now. 

doc/src/sgml/ref/create_view.sgml, some places also need to be updated, I think.
see text ON CONFLICT UPDATE in there.
I checked this before and still think it’s not needed. It’s in a bit about *updatable* views, and seems obvious to me how DO SELECT would work with that? Not a hill I’m willing to die on though, but a suggested change would be appreciated.

--------

Re. Infection point testing - I think this is very cool but I’d be tempted to agree with Dean on leaving it out from this patch.

--------
Re. deferrable constraints - I’ve removed that bit from the docs. Thanks for handling that Dean.

--------

In conclusion:
Attached is v17, with: 
- Jians latest patches minus the injection point testing
- Doc for MVCC
- ExecOnConflictSelect with a default clause for lockStrength.

Thanks again for your help both Jian and Dean

Re: ON CONFLICT DO SELECT (take 3)

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
On Tue, Nov 25, 2025 at 9:24 PM Viktor Holmberg  wrote:
>
> In conclusion:
> Attached is v17, with:
> - Jians latest patches minus the injection point testing
> - Doc for MVCC
> - ExecOnConflictSelect with a default clause for lockStrength.
>

hi.

+  
+   Insert a new distributor if the name doesn't match, otherwise return
+   the existing row.  This example uses the excluded
+   table in the WHERE clause to filter results:
+
+INSERT INTO distributors (did, dname) VALUES (12, 'Micro Devices Inc')
+    ON CONFLICT (did) DO SELECT WHERE dname = EXCLUDED.dname
+    RETURNING *;
+
+  

"ON CONFLICT (did)":
"Insert a new distributor if the name doesn't match",
i think it should be
"Insert a new distributor if the distributor id doesn't match",
suppose "did" refer to distributor id.


  /*
- * If there is a WHERE clause, initialize state where it will
- * be evaluated, mapping the attribute numbers appropriately.
- * As with onConflictSet, we need to map partition varattnos
- * to the partition's tupdesc.
+ * For both ON CONFLICT DO UPDATE and ON CONFLICT DO SELECT,
+ * there may be a WHERE clause.  If so, initialize state where
+ * it will be evaluated, mapping the attribute numbers
+ * appropriately.  As with onConflictSet, we need to map
+ * partition varattnos twice, to catch both the EXCLUDED
+ * pseudo-relation (INNER_VAR), and the main target relation
+ * (firstVarno).
  */
  if (node->onConflictWhere)
  {
  List   *clause;

+ if (part_attmap == NULL)
+ part_attmap =
+ build_attrmap_by_name(RelationGetDescr(partrel),
+  RelationGetDescr(firstResultRel),
+  false);
+
we already processed onConflictSet. the above comments need change?


heap_lock_tuple comments:
        /*
         * This is possible, but only when locking a tuple for ON CONFLICT
         * UPDATE.  We return this value here rather than throwing an error in
         * order to give that case the opportunity to throw a more specific
         * error.
         */
+begin transaction isolation level read committed;
+insert into selfconflict values (10,1), (10,2) on conflict(f1) do
select for update returning *;
+ERROR:  ON CONFLICT DO SELECT command cannot affect row a second time
+HINT:  Ensure that no rows proposed for insertion within the same
command have duplicate constrained values.
+commit;

the above tests showing TM_Invisible is possible for ON CONFLICT DO SELECT.
so the above heap_lock_tuple comments also need change.


+--
+-- INSERT ... ON CONFLICT DO SELECT and Row-level security
+--
+
+SET SESSION AUTHORIZATION regress_rls_alice;
+DROP POLICY p3_with_all ON document;
+
+CREATE POLICY p1_select_novels ON document FOR SELECT
+  USING (cid = (SELECT cid from category WHERE cname = 'novel'));
+CREATE POLICY p2_insert_own ON document FOR INSERT
+  WITH CHECK (dauthor = current_user);
+CREATE POLICY p3_update_novels ON document FOR UPDATE
+  USING (cid = (SELECT cid from category WHERE cname = 'novel'))
+  WITH CHECK (dauthor = current_user);
+
+SET SESSION AUTHORIZATION regress_rls_bob;

create_policy.sgml "Policies Applied by Command Type" distinguish ON
CONFLICT SELECT FOR UPDATE
and ON CONFLICT SELECT is that update will invoke the UPDATE USING policy.

The above tests p1_select_novels, p3_update_novels have the same using part.
SELECT FOR UPDATE will fail just like the same reason as ON CONFLICT SELECT
so I think the above tests do not fully test the SELECT FOR UPDATE scarenio.
please check the attached file, which slightly changed
p3_update_novels USING qual.


one minor issue, ruleutils.c: get_lock_clause_strength
I think it make more sense to remove the prefix whitespace, like change
``return " FOR KEY SHARE";``
to
``return "FOR KEY SHARE";``
and let caller add the whitespace itself.


--
jian
https://www.enterprisedb.com/

Re: ON CONFLICT DO SELECT (take 3)

От:
Viktor Holmberg <v@viktorh.net>
Дата:
Вложения:
On 28 Nov 2025 at 09:43 +0100, jian he <jian.universality@gmail.com>, wrote:
On Tue, Nov 25, 2025 at 9:24 PM Viktor Holmberg <v@viktorh.net> wrote:

In conclusion:
Attached is v17, with:
- Jians latest patches minus the injection point testing
- Doc for MVCC
- ExecOnConflictSelect with a default clause for lockStrength.


hi.

+ <para>
+ Insert a new distributor if the name doesn't match, otherwise return
+ the existing row. This example uses the <varname>excluded</varname>
+ table in the WHERE clause to filter results:
+<programlisting>
+INSERT INTO distributors (did, dname) VALUES (12, 'Micro Devices Inc')
+ ON CONFLICT (did) DO SELECT WHERE dname = EXCLUDED.dname
+ RETURNING *;
+</programlisting>
+ </para>

"ON CONFLICT (did)":
"Insert a new distributor if the name doesn't match",
i think it should be
"Insert a new distributor if the distributor id doesn't match",
suppose "did" refer to distributor id.
You are correct, fixed


/*
- * If there is a WHERE clause, initialize state where it will
- * be evaluated, mapping the attribute numbers appropriately.
- * As with onConflictSet, we need to map partition varattnos
- * to the partition's tupdesc.
+ * For both ON CONFLICT DO UPDATE and ON CONFLICT DO SELECT,
+ * there may be a WHERE clause. If so, initialize state where
+ * it will be evaluated, mapping the attribute numbers
+ * appropriately. As with onConflictSet, we need to map
+ * partition varattnos twice, to catch both the EXCLUDED
+ * pseudo-relation (INNER_VAR), and the main target relation
+ * (firstVarno).
*/
if (node->onConflictWhere)
{
List *clause;

+ if (part_attmap == NULL)
+ part_attmap =
+ build_attrmap_by_name(RelationGetDescr(partrel),
+ RelationGetDescr(firstResultRel),
+ false);
+
we already processed onConflictSet. the above comments need change?
I’m not sure I’m following here - the comment is just saying that we’re gonna do something 
similar to how we did for onConflictSet code which is above. So the comment is right I think - 
But regardless I’ve rewritten it to be more clear.
If this is not what you meant, let me know.

heap_lock_tuple comments:
/*
* This is possible, but only when locking a tuple for ON CONFLICT
* UPDATE. We return this value here rather than throwing an error in
* order to give that case the opportunity to throw a more specific
* error.
*/
+begin transaction isolation level read committed;
+insert into selfconflict values (10,1), (10,2) on conflict(f1) do
select for update returning *;
+ERROR: ON CONFLICT DO SELECT command cannot affect row a second time
+HINT: Ensure that no rows proposed for insertion within the same
command have duplicate constrained values.
+commit;

the above tests showing TM_Invisible is possible for ON CONFLICT DO SELECT.
so the above heap_lock_tuple comments also need change.
Right, I’ve updated the comment

+--
+-- INSERT ... ON CONFLICT DO SELECT and Row-level security
+--
+
+SET SESSION AUTHORIZATION regress_rls_alice;
+DROP POLICY p3_with_all ON document;
+
+CREATE POLICY p1_select_novels ON document FOR SELECT
+ USING (cid = (SELECT cid from category WHERE cname = 'novel'));
+CREATE POLICY p2_insert_own ON document FOR INSERT
+ WITH CHECK (dauthor = current_user);
+CREATE POLICY p3_update_novels ON document FOR UPDATE
+ USING (cid = (SELECT cid from category WHERE cname = 'novel'))
+ WITH CHECK (dauthor = current_user);
+
+SET SESSION AUTHORIZATION regress_rls_bob;

create_policy.sgml "Policies Applied by Command Type" distinguish ON
CONFLICT SELECT FOR UPDATE
and ON CONFLICT SELECT is that update will invoke the UPDATE USING policy.

The above tests p1_select_novels, p3_update_novels have the same using part.
SELECT FOR UPDATE will fail just like the same reason as ON CONFLICT SELECT
so I think the above tests do not fully test the SELECT FOR UPDATE scarenio.
please check the attached file, which slightly changed
p3_update_novels USING qual.
You’re right, the attached v18 includes those test changes

one minor issue, ruleutils.c: get_lock_clause_strength
I think it make more sense to remove the prefix whitespace, like change
``return " FOR KEY SHARE";``
to
``return "FOR KEY SHARE";``
and let caller add the whitespace itself.
I 100% agree, but this spacing behaviour seems to be a pattern in ruleutils:
{
 appendStringInfoString(buf, " ORDER BY ");
...
 appendContextKeyword(context, " OFFSET ",
...
appendContextKeyword(context, " WHERE ",

So removing the leading space for get_lock_clause_strength seems it’d cause problems by not being consistent, thus necessitating a bigger change in the code. So I’d prefer to do that as a separate change so as to not further increase the diff for this.

-------

Attaching v18 with the above changes. Thanks your continued reviews Jian!

Re: ON CONFLICT DO SELECT (take 3)

От:
jian he <jian.universality@gmail.com>
Дата:
On Sat, Nov 29, 2025 at 6:02 AM Viktor Holmberg  wrote:
>
> Attaching v18 with the above changes. Thanks your continued reviews Jian!
>

hi.
I had some minor comments with doc, comments.

+   expressions or condition. If using a
+   WHERE with ON CONFLICT DO UPDATE /
SELECT ,
+   you must have SELECT privilege on the columns referenced
+   in the WHERE clause.
the extra white space is not necessary, it should be:
ON CONFLICT DO UPDATE / SELECT


-   list of SELECT.  Only rows that were successfully
+   list of SELECT.  If an ON CONFLICT DO
SELECT
+   clause is not present, only rows that were successfully
    inserted or updated will be returned.  For example, if a row was
    locked but not updated because an ON CONFLICT DO UPDATE
    ... WHERE clause condition was not satisfied, the
-   row will not be returned.
+   row will not be returned.  ON CONFLICT DO SELECT
+   works similarly, except no update takes place.
I am not sure "except no update takes place." is appropriate here.


-   rows.  Similarly, if a DELETE is turned into an
+   rows.  Similarly, in an INSERT with an
+   ON CONFLICT DO SELECT clause, you can look at
the old values to determine if your query inserted a row or not. If a
DELETE is turned into an
    UPDATE by a rewrite rule,
    the new values may be non-NULL.
182 characters, line too long, we can wrap it into several lines.

src/backend/executor/execIndexing.c top have bunch of comments for
INSERT ... ON CONFLICT DO UPDATE/NOTHING
maybe we also need to write something for INSERT ON CONFLICT DO SELECT too.


src/backend/optimizer/plan/setrefs.c, fix_join_expr comments:
 * 3) ON CONFLICT UPDATE SET/WHERE clauses.  Here references to EXCLUDED are
 *      to be replaced with INNER_VAR references, while leaving target Vars (the
 *      to-be-updated relation) alone. Correspondingly inner_itlist is to be
 *      EXCLUDED elements, outer_itlist = NULL and acceptable_rel the target
 *      relation.
This applies to INSERT ON CONFLICT DO SELECT.
comments need slightly adjusted?


src/test/regress/sql/triggers.sql:
--
-- Verify behavior of before and after triggers with INSERT...ON CONFLICT
-- DO UPDATE
--
the above comments need change.
we can also add a new tests like:
``insert into upsert values(9, 'orange') on conflict (key) do select
for update returning old.*, new.*, upsert.*;``
then we can see how triggers behave with or without conflict.


https://git.postgresql.org/cgit/postgresql.git/commit/?id=2bc7e886fc1baaeee3987a141bff3ac490037d12
so we also need change infer_arbiter_indexes accordingly.
seems we only need adjust:
```
        else if (indexOidFromConstraint != InvalidOid)
        {
            /*
             * In the case of "ON constraint_name DO UPDATE" we need to skip
             * non-unique candidates.
             */
            if (!idxForm->indisunique && onconflict->action ==
ONCONFLICT_UPDATE)
                continue;
        }
```

src/test/regress/sql/updatable_views.sql tests line too long too, we can make it
into separate lines.


+insert into parted_conflict_test (a, b) values (1, 'x'), (2, 'y'),
(4, 'z') on conflict (a) do select returning *;
+
we can change it to
+insert into parted_conflict_test (a, b) values (1, 'x'), (2, 'y'), (4, 'z')
+  on conflict (a) do select returning *, tableoid::regclass;
then we can see that tableoid system is computed correctly in
ExecOnConflictSelect.


+ if (lockStrength == LCS_NONE)
+ {
+ if (!table_tuple_fetch_row_version(relation, conflictTid,
SnapshotAny, existing))
+ /* The pre-existing tuple was deleted */
+ return false;
+ }
i think this part should be
```
    if (!table_tuple_fetch_row_version(rel, conflictTid, SnapshotAny, existing))
        elog(ERROR, "failed to fetch conflicting tuple for ON CONFLICT");
```

say we have a conflict for values (1)
``insert into tsa values (1,3) on conflict(a) do select returning *;``

set a GDB breakpoint at ExecOnConflictSelect, let another process do
``delete from tsa; vacuum tsa;``
then let GDB continue.

table_tuple_fetch_row_version can still fetch the tuple.
so I think this is an unlikely scenario.



--
jian
https://www.enterprisedb.com


Re: ON CONFLICT DO SELECT (take 3)

От:
Viktor Holmberg <v@viktorh.net>
Дата:
Вложения:
On 12 Dec 2025 at 07:15 +0100, jian he <jian.universality@gmail.com>, wrote:
On Sat, Nov 29, 2025 at 6:02 AM Viktor Holmberg <v@viktorh.net> wrote:

Attaching v18 with the above changes. Thanks your continued reviews Jian!

hi.
I had some minor comments with doc, comments.
Thanks, all changed now.
+ if (lockStrength == LCS_NONE)
+ {
+ if (!table_tuple_fetch_row_version(relation, conflictTid,
SnapshotAny, existing))
+ /* The pre-existing tuple was deleted */
+ return false;
+ }
i think this part should be
```
if (!table_tuple_fetch_row_version(rel, conflictTid, SnapshotAny, existing))
elog(ERROR, "failed to fetch conflicting tuple for ON CONFLICT");
```

say we have a conflict for values (1)
``insert into tsa values (1,3) on conflict(a) do select returning *;``

set a GDB breakpoint at ExecOnConflictSelect, let another process do
``delete from tsa; vacuum tsa;``
then let GDB continue.

table_tuple_fetch_row_version can still fetch the tuple.
so I think this is an unlikely scenario.
Ok, I find this change slightly scary, but I’ve now changed this to assert that table_tuple_fetch_row_version is true. You say “unlikely” but having looked at it for a while I can’t see any case where it’d happen. Hence an assert seems most appropriate. I was thinking about asserting it even before the if as I believe the tuple should always be physically present, but I didn’t dare to. If anyone can think of a case where it’d happen I’d love to hear it!

/Viktor

Re: ON CONFLICT DO SELECT (take 3)

От:
"v@viktorh.net" <v@viktorh.net>
Дата:
Jian, am I ok to change the commitfest entry to “waiting for committer” or did you want to make another pass?

/Viktor

Re: ON CONFLICT DO SELECT (take 3)

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
On Tue, Jan 13, 2026 at 5:50 PM v@viktorh.net  wrote:
>
> Jian, am I ok to change the commitfest entry to “waiting for committer” or did you want to make another pass?
>
> /Viktor

hi.

There are some white spaces in v19.
it's time to squash the patchset into one, IMHO.
you can also begin to write the draft commit message, explain what this is all
about.

+ /*
+ * If rule_action is INSERT .. ON CONFLICT DO SELECT, the parser should
+ * have verified that it has a RETURNING clause, but we must also check
+ * that the triggering query has a RETURNING clause.
+ */
+ if (rule_action->onConflict &&
+ rule_action->onConflict->action == ONCONFLICT_SELECT &&
+ (!rule_action->returningList || !parsetree->returningList))
+ ereport(ERROR,
+ errcode(ERRCODE_SYNTAX_ERROR),
+ errmsg("ON CONFLICT DO SELECT requires a RETURNING clause"),
+ errdetail("A rule action is INSERT ... ON CONFLICT DO SELECT, which
requires a RETURNING clause."));
+
the errmsg, errdetail conveyed information seems duplicated somehow,
maybe we can merge it into one errmsg.

infer_arbiter_indexes
    /*
     * Quickly return NIL for ON CONFLICT DO NOTHING without an inference
     * specification or named constraint.  ON CONFLICT DO UPDATE statements
     * must always provide one or the other (but parser ought to have caught
     * that already).
     */
    if (onconflict->arbiterElems == NIL &&
        onconflict->constraint == InvalidOid)
        return NIL;
comments section, "ON CONFLICT DO UPDATE"
should be "ON CONFLICT DO SELECT/UPDATE" ?

ExecOnConflictSelect
    if (lockStrength == LCS_NONE)
    {
        /* Evem if the tuple is deleted, it must still be physically present */
        Assert(table_tuple_fetch_row_version(relation, conflictTid,
SnapshotAny, existing));
    }
this is wrong, i think.
buildtype=release, the Assert macro will always be true,
the whole Assert may be optimized out,
and later code would have trouble using (TupleTableSlot *existing).


* In the special case of an UPDATE arising from an
* INSERT ... ON CONFLICT DO UPDATE, existing records are first checked using
* a WCO_RLS_CONFLICT_CHECK WithCheckOption, which always uses the USING
* clauses from RLS policies.

the above comments in function add_with_check_options also need to be adjusted
for ON CONFLICT DO SELECT?


doc/src/sgml/ref/insert.sgml:
   If ON CONFLICT DO SELECT is used with
   FOR UPDATE or FOR SHARE,
   UPDATE privilege is also required on at least one
   column, in addition to SELECT privilege.

I am not sure this is accurate, may we can rephrase it as the following:

If ON CONFLICT DO SELECT is present,
SELECT privilege on the table is required.
If ON CONFLICT DO SELECT is used with a specified lock
strength, the UPDATE privilege is required on at least one
column, in addition to SELECT privilege.


dml.sgml

can still be useful for those commands.  For example, in an
INSERT with an
ON CONFLICT DO UPDATE
clause, the old values will be non-NULL for conflicting
rows.  Similarly, in an INSERT with an
ON CONFLICT DO SELECT clause, you can look at the old
values to determine if your query inserted a row or not.

for the above last sentence, maybe we can rephrase it as the following:
"""
Similarly, in an INSERT with an
ON CONFLICT DO SELECT clause,
the old values will be non-NULL for conflicting rows.
"""

create_policy.sgml
       
         If a data-modifying query has a RETURNING clause,
         SELECT permissions are required on the relation,
         and any newly inserted or updated rows from the relation must satisfy
         the relation's SELECT policies in order to be
         available to the RETURNING clause.  If a newly
         inserted or updated row does not satisfy the relation's
         SELECT policies, an error will be thrown (inserted
         or updated rows to be returned are never
         silently ignored).
       
we also need to update the above paragraph for ON CONFLICT DO SELECT?

create_policy.sgml
         If an INSERT has an ON CONFLICT DO
         NOTHING/UPDATE clause, SELECT
         permissions are required on the relation, and the rows proposed for
         insertion are checked using the relation's SELECT
         policies.
this part also needs to change for ON CONFLICT DO SELECT?

create_policy.sgml
     
      UPDATE
This section needs change for ON CONFLICT DO SELECT.


create_view.sgml
INSERT statements that have an
ON CONFLICT DO UPDATE clause are fully supported.

The above para needs change, since ON CONFLICT DO SELECT is also supported.

create_view.sgml
 (ON CONFLICT DO UPDATE may
    similarly affect an existing row not visible through the view).
the above sentence also needs change for ON CONFLICT DO SELECT?


ExecProcessReturning
 * newSlot: slot holding new tuple inserted or updated
 * planSlot: slot holding tuple returned by top subplan node
Do we need to refactor the above comments for the ON CONFLICT DO SELECT?

maybe we can change the comment
"ON CONFLICT SELECT" to "ON CONFLICT DO SELECT"

+ default:
+ elog(ERROR, "unexpected lock strength %d", lockStrength);
minor issue, we can cast it to int, like ``(int) lockStrength``.

src/backend/executor/execPartition.c changes look good to me.

updatable_views.sql: I did some ON CONFLICT DO SELECT permissions checks, and
other tests in it, please check attached.


--
jian
https://www.enterprisedb.com

Re: ON CONFLICT DO SELECT (take 3)

От:
Viktor Holmberg <v@viktorh.net>
Дата:
Вложения:
There are some white spaces in v19.
Sorry, what do you mean "white spaces”? Is it a problem?
it's time to squash the patchset into one, IMHO.
you can also begin to write the draft commit message, explain what this is all
about.
Yes, done.
ExecOnConflictSelect
if (lockStrength == LCS_NONE)
{
/* Evem if the tuple is deleted, it must still be physically present */
Assert(table_tuple_fetch_row_version(relation, conflictTid,
SnapshotAny, existing));
}
this is wrong, i think.
buildtype=release, the Assert macro will always be true,
the whole Assert may be optimized out,
and later code would have trouble using (TupleTableSlot *existing).
Yes, you’re right. Nice catch. Fixed.
updatable_views.sql: I did some ON CONFLICT DO SELECT permissions checks, and
other tests in it, please check attached.
Added

-----
I’ve updated all the comments you mentioned.
Thanks for the review Jian, I’m hoping we’ve caught all the issues now.
Please find v20 attached.

Re: ON CONFLICT DO SELECT (take 3)

От:
Viktor Holmberg <v@viktorh.net>
Дата:
Вложения:
On 21 Jan 2026 at 21:06 +0100, Viktor Holmberg <v@viktorh.net>, wrote:
There are some white spaces in v19.
Sorry, what do you mean "white spaces”? Is it a problem?
it's time to squash the patchset into one, IMHO.
you can also begin to write the draft commit message, explain what this is all
about.
Yes, done.
ExecOnConflictSelect
if (lockStrength == LCS_NONE)
{
/* Evem if the tuple is deleted, it must still be physically present */
Assert(table_tuple_fetch_row_version(relation, conflictTid,
SnapshotAny, existing));
}
this is wrong, i think.
buildtype=release, the Assert macro will always be true,
the whole Assert may be optimized out,
and later code would have trouble using (TupleTableSlot *existing).
Yes, you’re right. Nice catch. Fixed.
updatable_views.sql: I did some ON CONFLICT DO SELECT permissions checks, and
other tests in it, please check attached.
Added

-----
I’ve updated all the comments you mentioned.
Thanks for the review Jian, I’m hoping we’ve caught all the issues now.
Please find v20 attached.
I went through all mentions of ON CONFLICT in the codebase to see there are no more forgotten comments/docs, and found 2 more places to update.

Re: ON CONFLICT DO SELECT (take 3)

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
On Thu, Jan 22, 2026 at 4:05 AM Viktor Holmberg  wrote:
>
> There are some white spaces in v19.
>
> Sorry, what do you mean "white spaces”? Is it a problem?

you can use ``git diff --check`` to find out these white spaces.
The attached file should be able to fix these issues.

+-- DO SELECT FOR UPDATE requires UPDATE rights, should fail for non-novel
+INSERT INTO document VALUES (33, (SELECT cid from category WHERE
cname = 'science fiction'), 1, 'regress_rls_bob', 'another sci-fi')
+    ON CONFLICT (did) DO SELECT FOR UPDATE RETURNING did, dauthor, dtitle;
+ERROR:  new row violates row-level security policy for table "document"

The above comment is wrong. If i place

INSERT INTO document VALUES (33, (SELECT cid from category WHERE cname
= 'science fiction'), 1, 'regress_rls_bob', 'another sci-fi')
ON CONFLICT (did) DO NOTHING;

before the above tests, it will still fail, it will fail on SELECT
policy, p1_select_novels.
we can remove the above tests or rephrase the comment.

+CREATE POLICY p3_update_novels ON document FOR UPDATE
+  USING (cid = (SELECT cid from category WHERE cname = 'novel') AND dlevel = 1)
+  WITH CHECK (dauthor = current_user);

My understanding of the change in get_row_security_policies is that, ON CONFLICT
DO SELECT FOR UPDATE, the UPDATE WITH CHECK policy clause is never evaluated.
For testing purposes, we could change  the above
+WITH CHECK (dauthor = current_user);
to
+WITH CHECK (dauthor = current_user AND false);

This leads to the next issue in ExecOnConflictSelect->ExecWithCheckOptions.
+ if (resultRelInfo->ri_WithCheckOptions != NIL)
+ {
+ /*
+ * Check target's existing tuple against SELECT-applicable USING
+ * security barrier quals (if any), enforced here as RLS checks/WCOs.
+ *
+ * The rewriter creates SELECT RLS checks/WCOs for SELECT security
+ * quals, and stores them as WCOs of "kind" WCO_RLS_CONFLICT_CHECK. If
+ * FOR UPDATE/SHARE was specified, UPDATE rights are required on the
+ * target table, and the rewriter also adds UPDATE RLS checks/WCOs for
+ * UPDATE security quals, using WCOs of the same kind, so this check
+ * enforces them too.
+ */
+ ExecWithCheckOptions(WCO_RLS_CONFLICT_CHECK, resultRelInfo,
+ existing,
+ mtstate->ps.state);
+ }
the comment I am not sure I fully understand, especially the last sentence.

My understanding is that
For ON CONFLICT DO SELECT FOR UPDATE, both the SELECT USING and UPDATE USING
clauses are evaluated.  If either evaluates to false, the row is not silently
ignored; instead, an error is raised.
UPDATE CHECK clause was never evaluated.

Maybe we need to rephrase the above comments.

>
> it's time to squash the patchset into one, IMHO.
> you can also begin to write the draft commit message, explain what this is all
> about.
>
> Yes, done.
>
> ExecOnConflictSelect
> if (lockStrength == LCS_NONE)
> {
> /* Evem if the tuple is deleted, it must still be physically present */
> Assert(table_tuple_fetch_row_version(relation, conflictTid,
> SnapshotAny, existing));
> }
> this is wrong, i think.
> buildtype=release, the Assert macro will always be true,
> the whole Assert may be optimized out,
> and later code would have trouble using (TupleTableSlot *existing).
>
> Yes, you’re right. Nice catch. Fixed.
>

it still have problem with release branch,
see https://cirrus-ci.com/task/5061396800471040?logs=gcc_warning#L454

I intended to change it as
```
    if (lockStrength == LCS_NONE)
    {
        if (!table_tuple_fetch_row_version(relation,
                                           conflictTid,
                                           SnapshotAny,
                                           existing))
            elog(ERROR, "failed to fetch conflicting tuple for ON CONFLICT");
    }
```

     * For ON CONFLICT .. UPDATE we just need the inner tlist to point to the
     * excluded expression's tlist. (Similar to the SubqueryScan we don't want
     * to reuse OUTER, it's used for RETURNING in some modify table cases,
     * although not INSERT .. CONFLICT).
the above comments in set_deparse_plan need apply to ON CONFLICT DO SELECT


typedef enum WCOKind, WCOKind
WCO_RLS_CONFLICT_CHECK,        /* RLS ON CONFLICT DO UPDATE USING policy */
the comments need to be adjusted.

The discussion link should be these three.
Discussion: https://postgr.es/m/5fca222d-62ae-4a2f-9fcb-0eca56277094@Spark
Discussion: https://postgr.es/m/2b5db2e6-8ece-44d0-9890-f256fdca9f7e@proxel.se
Discussion: https://postgr.es/m/d631b406-13b7-433e-8c0b-c6040c4b4663@Spark

Since there have been some discussions about the author, we can also mention
authors in the commit message.

Re: ON CONFLICT DO SELECT (take 3)

От:
jian he <jian.universality@gmail.com>
Дата:
Hi.

       
         Note that an INSERT with an ON CONFLICT
         clause will check the INSERT policies'

We need to change it to ON CONFLICT otherwise doc
build will fail.


doc/src/sgml/ref/create_policy.sgml
       
         When an INSERT command has an auxiliary
         ON CONFLICT DO UPDATE clause, if the
         UPDATE path is taken, the row to be updated is
         first checked against the USING expressions of
For ON CONFLICT DO SELECT, perhaps we should add some explanatory text
to the preceding paragraph?


doc/src/sgml/ref/create_policy.sgml
   
    Policies Applied by Command Type
The change in this section looks correct to me.


doc/src/sgml/ref/insert.sgml
However, ON CONFLICT DO UPDATE
   also requires SELECT privilege on any column whose
   values are read in the ON CONFLICT DO UPDATE
   expressions or condition. If using a
   WHERE with ON CONFLICT DO UPDATE /
SELECT,
   you must have SELECT privilege on the columns referenced
   in the WHERE clause.

condition is the same thing as
WHERE clause.
so here, you mentioned twice that ON CONFLICT DO UPDATE requires
SELECT privilege
on columns referenced by the WHERE clause.
So, I think the last sentence can just be
"""
If using a WHERE with ON CONFLICT DO SELECT, you must have SELECT privilege on
the columns referenced in the WHERE clause.
"""


ExecProcessReturning comment:
 * oldSlot: slot holding old tuple deleted or updated
 * newSlot: slot holding new tuple inserted or updated, or existing tuple
 *          selected (for ON CONFLICT DO SELECT)

"oldSlot" comment also needs slight adjustment.


typedef struct RTEPermissionInfo
comment:
 * For SELECT/INSERT/UPDATE permissions, if the user doesn't have table-wide
 * permissions then it is sufficient to have the permissions on all columns
 * identified in selectedCols (for SELECT) and/or insertedCols and/or
 * updatedCols (INSERT with ON CONFLICT DO UPDATE may have all 3).

This applies to ON CONFLICT DO SELECT FOR UPDATE, i think.
Maybe we can update this too.


Overall, these are all the issues I’ve identified. Aside from those
issues, the patch looks very good.


--
jian
https://www.enterprisedb.com


Re: ON CONFLICT DO SELECT (take 3)

От:
Viktor Holmberg <v@viktorh.net>
Дата:
Вложения:
On 28 Jan 2026 at 09:53 +0100, jian he <jian.universality@gmail.com>, wrote:

doc/src/sgml/ref/create_policy.sgml
<para>
When an <literal>INSERT</literal> command has an auxiliary
<literal>ON CONFLICT DO UPDATE</literal> clause, if the
<literal>UPDATE</literal> path is taken, the row to be updated is
first checked against the <literal>USING</literal> expressions of
For ON CONFLICT DO SELECT, perhaps we should add some explanatory text
to the preceding paragraph?
I think this is overkill. The previous paragraph talks about the returning clause, and in general I think the behaviour is obvious? Or did you have anything specific in mind?
typedef struct RTEPermissionInfo
comment:
* For SELECT/INSERT/UPDATE permissions, if the user doesn't have table-wide
* permissions then it is sufficient to have the permissions on all columns
* identified in selectedCols (for SELECT) and/or insertedCols and/or
* updatedCols (INSERT with ON CONFLICT DO UPDATE may have all 3).

This applies to ON CONFLICT DO SELECT FOR UPDATE, i think.
Maybe we can update this too.
I think the comment is clear enough as is - the example about ON CONFLCIT DO UPDATE is just to illustrate how it works. Adding details about DO SELECT seems out of place here? No a hill I'm willing to die on but maybe you can suggest something if you disagree Jian?
Overall, these are all the issues I’ve identified. Aside from those
issues, the patch looks very good.

--
jian
Here comes v.22 with all your comments except those 2 mentioned above updated in line with your comments Jian.
I squashed everything together - if you’d rather have the fixes as a separate commit for review let me know.
Thanks again for your detailed feedback & fixes. I’m sorry you’ve had to go though so many iterations of review on this one, but hopefully it’s starting to look ok now.

/Viktor

Re: ON CONFLICT DO SELECT (take 3)

От:
jian he <jian.universality@gmail.com>
Дата:
hi.

v22 looks good to me.
I have marked this as "Ready for Committer".

+   
+    INSERT with an ON CONFLICT DO
+    SELECT clause behaves similarly to ON CONFLICT DO
+    UPDATE. In Read Committed mode, if a conflict originates
+    in another transaction whose effects are not yet visible to the
+    INSERT, the SELECT clause will
+    return that row, even though possibly no version
+    of that row is conventionally visible to the command.
+   
+
I think I understand the above paragraph.

however the preceding paragraph (doc/src/sgml/mvcc.sgml), we have:
"""
In Read Committed mode, each row proposed for insertion
    will either insert or update. Unless there are unrelated errors, one of
    those two outcomes is guaranteed.
"""
Maybe we can write something similar for INSERT ON CONFLICT?



--
jian
https://www.enterprisedb.com


Re: ON CONFLICT DO SELECT (take 3)

От:
Viktor Holmberg <v@viktorh.net>
Дата:
Вложения:
On 4 Feb 2026 at 11:23 +0100, jian he <jian.universality@gmail.com>, wrote:
hi.

v22 looks good to me.
I have marked this as "Ready for Committer".
Thanks! Appreciate the reviews!

+ <para>
+ <command>INSERT</command> with an <literal>ON CONFLICT DO
+ SELECT</literal> clause behaves similarly to <literal>ON CONFLICT DO
+ UPDATE</literal>. In Read Committed mode, if a conflict originates
+ in another transaction whose effects are not yet visible to the
+ <command>INSERT</command>, the <literal>SELECT</literal> clause will
+ return that row, even though possibly <emphasis>no</emphasis> version
+ of that row is conventionally visible to the command.
+ </para>
+
I think I understand the above paragraph.

however the preceding paragraph (doc/src/sgml/mvcc.sgml), we have:
"""
In Read Committed mode, each row proposed for insertion
will either insert or update. Unless there are unrelated errors, one of
those two outcomes is guaranteed.
"""
Maybe we can write something similar for INSERT ON CONFLICT?
The wording was quite confusing and overly theoretical. I’ve re-written it to try and explain it a more plainly:

"
INSERT with an ON CONFLICT DO SELECT clause behaves similarly to ON CONFLICT DO UPDATE. In Read Committed mode, each row proposed for insertion is guaranteed to either insert or return the conflicting row (unless there are unrelated errors). If a conflict originates in another transaction whose effects are not yet visible to the INSERT, the command will wait for that transaction to commit or roll back, then return the conflicting row if it was committed (even though that row was not visible when the command started).
"

That change is squashed into v23. I was thinking about also updating the DO UPDATE paragraph but decided against it.

Re: ON CONFLICT DO SELECT (take 3)

От:
Dean Rasheed <dean.a.rasheed@gmail.com>
Дата:
Вложения:
On Wed, 4 Feb 2026 at 12:52, Viktor Holmberg  wrote:
>
> On 4 Feb 2026 at 11:23 +0100, jian he , wrote:
>
> I have marked this as "Ready for Committer".
>

I have been going over this, with an eye to committing it.

I'm not convinced that the pgrowlocks tests are worth it. It's quite a
lot of new code to test something quite trivial, and it doesn't seem
worth carrying that code going forward. I think there is sufficient
coverage in other tests, so I have removed these.

Looking at the first change to create_policy.sgml, it's not quite
right, but on closer inspection neither was the original text. The
issue is that in the case of an INSERT ... ON CONFLICT DO NOTHING,
SELECT policies are only applied if an arbiter clause is present.
Since that's a pre-existing bug, it should be fixed and back-patched
separately -- see 0001, attached.

Looking at the paragraph on insert.sgml describing column privileges
required, I realised that there is another pre-existing bug there --
it fails to mention privileges required by columns referred to by the
arbiter index/constraint, and this applies to all forms of ON
CONFLICT, not just DO UPDATE. Again, I think that should be fixed and
back-patched separately, which I've done in 0002, in a way intended to
need no update for ON CONFLICT DO SELECT.

I don't really like that ExecOnConflictSelect() passes CMD_INSERT to
ExecProcessReturning(), because that's inconsistent with
ExecOnConflictUpdate(). We could pass CMD_SELECT, adding a new case to
the switch statement, but I think a neater solution is to change the
cmdType parameter to a bool "isDelete" parameter, which makes the code
slightly simpler, because only the DELETE case behaves differently
from other cases. I considered pulling this out as a separate commit,
but I don't think that it's really worth it.

In rewriteRuleAction(), when the rule action is INSERT .. ON CONFLICT
DO SELECT but the triggering query lacks a RETURNING clause, I think
that the errdetail() that an earlier version of the patch had was
useful. The reason is that the triggering query will have been a plain
INSERT, with no ON CONFLICT clause, so the primary error message might
be confusing without the additional information that a rule rewrote
the query, turning it into an INSERT ... ON CONFLICT DO SELECT. So I
have put that errdetail() back.

In insert_conflict.sql, the permission tests looked out of place, and
a little long-winded, so I moved them to privileges.sql, which already
had suitable test tables, and I cut them down a bit, because it
doesn't really seem necessary to test every lock strength (we don't
for other commands). I also cut down some of the other tests, which
seemed a bit repetitive.

In rowsecurity.sql, I tweaked the first DO SELECT test to confirm that
the SELECT policy is applied to the existing row, in the event of
conflict. Also, note that DO SELECT FOR UPDATE is not exactly the same
as DO UPDATE, because it only applies UPDATE USING policy clauses, not
UPDATE CHECKs.

In triggers.sql, the new tests didn't really seem to be testing
anything new, since only INSERT triggers fire for DO SELECT, and for
the values used in the test cases, the triggers didn't change
anything. So I've replaced them with a single new test that confirms
that DO SELECT sees the values updated by the BEFORE INSERT trigger.

In updatable_views.sql, I've simplified a few of the tests which
seemed overly repetitive, and expanded some of the others.

Aside from those changes, I made a few other cosmetic changes. If
you're happy with those, I think it's pretty-much good-to-go.

(Though I need to wait for the release freeze to expire before I can
push and back-patch 0001 and 0002).

Regards,
Dean

Re: ON CONFLICT DO SELECT (take 3)

От:
Viktor Holmberg <v@viktorh.net>
Дата:

I have been going over this, with an eye to committing it.
Thanks for looking at this.
Looking at the first change to create_policy.sgml, it's not quite
right, but on closer inspection neither was the original text. The
issue is that in the case of an INSERT ... ON CONFLICT DO NOTHING,
SELECT policies are only applied if an arbiter clause is present.
Since that's a pre-existing bug, it should be fixed and back-patched
separately -- see 0001, attached.

Looking at the paragraph on insert.sgml describing column privileges
required, I realised that there is another pre-existing bug there --
it fails to mention privileges required by columns referred to by the
arbiter index/constraint, and this applies to all forms of ON
CONFLICT, not just DO UPDATE. Again, I think that should be fixed and
back-patched separately, which I've done in 0002, in a way intended to
need no update for ON CONFLICT DO SELECT.
Nice that you found this.

I don't really like that ExecOnConflictSelect() passes CMD_INSERT to
ExecProcessReturning(), because that's inconsistent with
ExecOnConflictUpdate(). We could pass CMD_SELECT, adding a new case to
the switch statement, but I think a neater solution is to change the
cmdType parameter to a bool "isDelete" parameter, which makes the code
slightly simpler, because only the DELETE case behaves differently
from other cases. I considered pulling this out as a separate commit,
but I don't think that it's really worth it.
Nice - as I mentioned earlier I noticed this was funky but I didn’t want to add 
more changes to review. But I’m glad you sorted it as it’s way nicer now.
Aside from those changes, I made a few other cosmetic changes. If
you're happy with those, I think it's pretty-much good-to-go.

(Though I need to wait for the release freeze to expire before I can
push and back-patch 0001 and 0002).

Regards,
Dean
Thanks for sorting all these changes Dean, all look good to me. The only 
thing that gave me pause is this change in analyse.c lines 1238-1247:

/* Process DO SELECT/UPDATE */
if (onConflictClause->action == ONCONFLICT_UPDATE ||
 onConflictClause->action == ONCONFLICT_SELECT)
{
/*
* Expressions in the UPDATE targetlist need to be handled like UPDATE
* not INSERT. We don't need to save/restore this because all INSERT
* expressions have been parsed already.
*/
pstate->p_is_insert = false;

So in v.24 we set p_is_insert = false for DO SELECT as well.
If I’m understanding the code correctly, this is only used when using indirection 
on target columns for updates, like setting a value inside an array, like for example:
update example set arr[2] = 10;
So changing this should have any effect, as the DO SELECT doesn’t have any SET clause.
Logically it makes sense that DO SELECT is p_is_insert = false.
But maybe the comment should be updated to explain this?
I’m not sure how to put it, but maybe:
/*
 * Expressions in the UPDATE targetlist need to be handled like UPDATE
 * not INSERT. For DO SELECT, this doesn't matter as there is no 
 * SET clause. We don't need to save/restore this because all INSERT
 * expressions have been parsed already.
 */
?

Best
/Viktor

Re: ON CONFLICT DO SELECT (take 3)

От:
Dean Rasheed <dean.a.rasheed@gmail.com>
Дата:
Вложения:
On Tue, 10 Feb 2026 at 21:59, Viktor Holmberg  wrote:
>
> Looking at the first change to create_policy.sgml, it's not quite
> right, but on closer inspection neither was the original text. The
> issue is that in the case of an INSERT ... ON CONFLICT DO NOTHING,
> SELECT policies are only applied if an arbiter clause is present.
> Since that's a pre-existing bug, it should be fixed and back-patched
> separately -- see 0001, attached.
>
> Looking at the paragraph on insert.sgml describing column privileges
> required, I realised that there is another pre-existing bug there --
> it fails to mention privileges required by columns referred to by the
> arbiter index/constraint, and this applies to all forms of ON
> CONFLICT, not just DO UPDATE. Again, I think that should be fixed and
> back-patched separately, which I've done in 0002, in a way intended to
> need no update for ON CONFLICT DO SELECT.
>
> Nice that you found this.

OK, I have pushed and back-patched 0001 and 0002.

> Thanks for sorting all these changes Dean, all look good to me. The only
> thing that gave me pause is this change in analyse.c lines 1238-1247:
>
> So in v.24 we set p_is_insert = false for DO SELECT as well.
> If I’m understanding the code correctly, this is only used when using indirection
> on target columns for updates, like setting a value inside an array, like for example:
> update example set arr[2] = 10;
> So changing this should have any effect, as the DO SELECT doesn’t have any SET clause.
> Logically it makes sense that DO SELECT is p_is_insert = false.
> But maybe the comment should be updated to explain this?

Yes, that's right. I was just trying to reduce code churn. However, if
we need to change the comment to explain why it's OK for DO SELECT,
the code churn argument doesn't work, and it's probably better to only
set it for DO UPDATE. So I've reverted it back to how it was in v23,
with slightly updated comments.

Re-reading the INSERT docs, I still wasn't entirely happy with the
description of the conflict_action parameter, so I had a go at
rewriting it. I also pulled out the description of the locking
options, describing them separately and linking to the description of
the locking clause on the SELECT page.

Regards,
Dean

Re: ON CONFLICT DO SELECT (take 3)

От:
Viktor Holmberg <v@viktorh.net>
Дата:
Вложения:
On 11 Feb 2026 at 12:34 +0100, Dean Rasheed <dean.a.rasheed@gmail.com>, wrote:
Thanks for sorting all these changes Dean, all look good to me. The only
thing that gave me pause is this change in analyse.c lines 1238-1247:

So in v.24 we set p_is_insert = false for DO SELECT as well.
If I’m understanding the code correctly, this is only used when using indirection
on target columns for updates, like setting a value inside an array, like for example:
update example set arr[2] = 10;
So changing this should have any effect, as the DO SELECT doesn’t have any SET clause.
Logically it makes sense that DO SELECT is p_is_insert = false.
But maybe the comment should be updated to explain this?

Yes, that's right. I was just trying to reduce code churn. However, if
we need to change the comment to explain why it's OK for DO SELECT,
the code churn argument doesn't work, and it's probably better to only
set it for DO UPDATE. So I've reverted it back to how it was in v23,
with slightly updated comments.
Looking more at this, I’m quite sure that the p_is_insert field can just be removed?
See 0002. If you’d rather focus on reducing code churn, or you believe this is risky, 
I’m also happy for you to just commit 0001.
Re-reading the INSERT docs, I still wasn't entirely happy with the
description of the conflict_action parameter, so I had a go at
rewriting it. I also pulled out the description of the locking
options, describing them separately and linking to the description of
the locking clause on the SELECT page.
Had a look through it and yes, the docs are better with your changes.

Re: ON CONFLICT DO SELECT (take 3)

От:
Dean Rasheed <dean.a.rasheed@gmail.com>
Дата:
On Wed, 11 Feb 2026 at 14:55, Viktor Holmberg  wrote:
>
> Looking more at this, I’m quite sure that the p_is_insert field can just be removed?
> See 0002.

Ah, good idea. Well spotted!

This dates back to c1ca3a1, which removed a similar p_is_update field,
but noted that using p_is_insert wasn't particularly pretty.

Going back even further, it looks like p_is_insert and p_is_update
used to be much more widely used, but now we're down to just this one
place in transformAssignedExpr() that reads p_is_insert, and as you
say, it can deduce the same information from the exprKind passed to
it, which is much neater.

Barring objections, I'll push both those shortly.

Regards,
Dean


Re: ON CONFLICT DO SELECT (take 3)

От:
Viktor Holmberg <v@viktorh.net>
Дата:
On 11 Feb 2026 at 17:11 +0100, Dean Rasheed <dean.a.rasheed@gmail.com>, wrote:
On Wed, 11 Feb 2026 at 14:55, Viktor Holmberg <v@viktorh.net> wrote:

Looking more at this, I’m quite sure that the p_is_insert field can just be removed?
See 0002.

Ah, good idea. Well spotted!

This dates back to c1ca3a1, which removed a similar p_is_update field,
but noted that using p_is_insert wasn't particularly pretty.

Going back even further, it looks like p_is_insert and p_is_update
used to be much more widely used, but now we're down to just this one
place in transformAssignedExpr() that reads p_is_insert, and as you
say, it can deduce the same information from the exprKind passed to
it, which is much neater.

Barring objections, I'll push both those shortly.
Certainly no objections from me! Excited to get this in.

/Viktor

Re: ON CONFLICT DO SELECT (take 3)

От:
Dean Rasheed <dean.a.rasheed@gmail.com>
Дата:
On Wed, 11 Feb 2026 at 16:28, Viktor Holmberg  wrote:
>
> On 11 Feb 2026 at 17:11 +0100, Dean Rasheed , wrote:
>
> Barring objections, I'll push both those shortly.
>
> Certainly no objections from me! Excited to get this in.
>

Pushed.

Regards,
Dean


FAQ