
create table inh_merge (key text, chain text);

create table inh_merge_1 (key text, chain text);
create table inh_merge_2 (chain text, key text, other text);
create table inh_merge_3 (dropme numeric, key text, chain text);
--alter table inh_merge_3 drop column dropme;

create table inh_mergeme (key text);


ALTER TABLE inh_merge_1 INHERIT inh_merge;
ALTER TABLE inh_merge_2 INHERIT inh_merge;
ALTER TABLE inh_merge_3 INHERIT inh_merge;

INSERT INTO inh_merge(key, chain) VALUES
 ('p-1', 'orig-p-1'),
 ('p-2', 'orig-p-2');

INSERT INTO inh_merge_1(key, chain) VALUES
 ('c1-1', 'orig-c1-1'),
 ('c1-2', 'orig-c1-2');

INSERT INTO inh_merge_2(key, chain) VALUES
 ('c2-1', 'orig-c2-1'),
 ('c2-2', 'orig-c2-2');

INSERT INTO inh_merge_3(key, chain) VALUES
 ('c3-1', 'orig-c3-1'),
 ('c3-2', 'orig-c3-2');

INSERT INTO inh_mergeme(key) VALUES
 ('p-1'),
 ('c1-1'),
 ('c2-1'),
 ('c3-1'),
 ('c1-3'),
 ('c2-3'),
 ('c3-3');

MERGE into inh_merge m
  using inh_mergeme s on (m.key = s.key)
WHEN MATCHED THEN UPDATE
  SET chain = ('merge-update-'||m.key)
WHEN NOT MATCHED THEN INSERT (key, chain)
  VALUES(key, 'merge-insert-'||key)
RETURNING m.tableoid::regclass, m.*;
