I want to insert in a ManyToMany relationship (between ‘fiche’ and quality) a line (same principle as a log) when an insertion fails because the key is duplicated.
example:
insert into fiche (content) values ('toto')
on conflict (content) do
insert into fiche_qualites (poi_id, qualites_id) values (idPoi, 'Code error');
My error:
ERROR: syntax error at or near "insert"
I’m in a loop doing mass inserts and I want to be able to keep track when I have a duplicate (detected by uniqueness).
2
Answers
You may use a PL/pgSQL block to catch an
unique_violation
exception and handle it.The block may be shaped as a reusable function too.
Triggers
are the most intuitive / flexible approach, but since your use case is only about keeping track of the duplicated entries in a separated table you can use aCTE
(aka WITH clause) returning thexmax
of the new records – new records always have axmax
= 0. Then finally in the outer query you filter only the inserted records to store in the "duplicates" table, e.g.Demo:
db<>fiddle