Estou tentando emular o MERGE
comportamento com pl/pgsql:
-- Generate the data from funtion
CREATE TEMP TABLE temp_x (id int, id2 int, data text, created_at timestamp, updated_at timestamp) ON COMMIT DROP;
INSERT INTO temp_x SELECT * FROM set_gernating_function(p);
-- DELETE record with same id2
DELETE FROM x WHERE NOT EXISTS (SELECT 1 FROM temp_x WHERE temp_x.id=x.id) AND id2=p.id2;
-- UPSERT by (id, id2)
INSERT INTO x
SELECT * FROM temp_x z
ON CONFLICT(id, id2) DO UPDATE
SET
updated_at=excluded.updated_at,
data=excluded.data;
Mas o uso da tabela temporária está gerando inchaço pg_class
e pg_attr
tabela muito rápido - Mais rápido do que eu poderia fazer vácuo - e afeta outras consultas. Qualquer ideia?
Existem algumas restrições:
- Preservar o
created_at
tempo se o id já existir - x tem um gatilho de exclusão, portanto, nenhuma exclusão desnecessária.
- o
set_generating_function
é lento - O tamanho para temp_x é pequeno. (< 50)
- A taxa de execução é muito alta (milhares por segundo)
Você não precisa da tabela temporária:
Você pode fazer isso em uma única instrução: