Re: MERGE ... RETURNING - Mailing list pgsql-hackers

From Dean Rasheed
Subject Re: MERGE ... RETURNING
Date
Msg-id CAEZATCXLv5LLKuN7CLaQGe3OtetEDpuTRXyR9u2_6BKO0bc6UA@mail.gmail.com
Whole thread Raw
In response to Re: MERGE ... RETURNING  (Jeff Davis <pgsql@j-davis.com>)
Responses Re: MERGE ... RETURNING
List pgsql-hackers
On Wed, 1 Nov 2023 at 17:49, Jeff Davis <pgsql@j-davis.com> wrote:
>
> Most of my concern is that parts of the implementation feel like a
> hack, which makes me concerned that we're approaching it the wrong way.
>

OK, that's a fair point. Attached is a new version, replacing those
parts of the implementation with a new MergingFunc node. It doesn't
add that much more complexity, and I think the new code is much
neater.

Also, I think this makes it easier / more natural to add additional
returning options, like Merlin's suggestion to return a user-defined
label value, though I haven't implemented that.

I have gone with the name originally suggested by Vik -- MERGING(),
which means that that has to be a new col-name keyword. I'm not
especially wedded to that name, but I think that it's not a bad
choice, and I think going with that is preferable to making MERGE a
col-name keyword.

So (quoting the example from the docs), the new syntax looks like this:

MERGE INTO products p
  USING stock s ON p.product_id = s.product_id
  WHEN MATCHED AND s.quantity > 0 THEN
    UPDATE SET in_stock = true, quantity = s.quantity
  WHEN MATCHED THEN
    UPDATE SET in_stock = false, quantity = 0
  WHEN NOT MATCHED THEN
    INSERT (product_id, in_stock, quantity)
      VALUES (s.product_id, true, s.quantity)
  RETURNING MERGING(ACTION), MERGING(CLAUSE_NUMBER), p.*;

 action | clause_number | product_id | in_stock | quantity
--------+---------------+------------+----------+----------
 UPDATE |             1 |       1001 | t        |       50
 UPDATE |             2 |       1002 | f        |        0
 INSERT |             3 |       1003 | t        |       10

By default, the returned column names are automatically taken from the
argument to the MERGING() function (which isn't actually a function
anymore).

There's one bug that I know about, to do with cross-partition updates,
but since that's a pre-existing bug, I'll start a new thread for it.

Regards,
Dean

Attachment

pgsql-hackers by date:

Previous
From: Bruce Momjian
Date:
Subject: Re: Version 14/15 documentation Section "Alter Default Privileges"
Next
From: David Steele
Date:
Subject: Re: Add recovery to pg_control and remove backup_label