Mapping MERGE onto CTEs (Re: MERGE SQL Statement for PG11)

Nico Williams <nico@cryptonector.com>

From: Nico Williams <nico@cryptonector.com>
To: Simon Riggs <simon@2ndquadrant.com>
Cc: PostgreSQL-development <pgsql-hackers@postgresql.org>
Date: 2017-11-01T16:56:20Z
Lists: pgsql-hackers
Is it possible to map MERGE onto a query with CTEs that does the the
various DMLs, with all but the last RETURNING?  Here's a sketch:

WITH matched_rows AS (
        SELECT FROM <target> t WHERE <condition>
     ),
     updated_rows AS (
        UPDATE <target> t
        SET ...
        WHERE ... AND t in (SELECT j FROM matched_rows j)
        RETURNING t
     ),
     inserted_rows AS (
        INSERT INTO <target> t
        SELECT ...
        WHERE ... AND t NOT IN (SELECT j FROM matched_rows j)
        RETURNING t
     ),
DELETE FROM <target> t
WHERE ...;

Now, one issue is that in PG CTEs are basically like temp tables, and
also like optimizer barriers, so this construction is not online, and if
matched_rows is very large, that would be a problem.

As an aside, I'd like to be able to control which CTEs are view-like and
which are table-like.  In SQLite3, for example, they are all view-like,
and the optimizer will act accordingly, whereas in PG they are all
table-like, and thus optimizer barriers.

Nico
-- 


Commits

  1. Add support for MERGE SQL command

  2. Add API of sorts for transition table handling in trigger.c

  3. Revert MERGE patch

  4. Fix several bugs related to ON CONFLICT's EXCLUDED pseudo relation.