3 ms·
For this I currently use: UPDATE Table SET ... WHERE id=$1 if (rows_updated == 0) { INSERT INTO Table ... WHERE NOT EXISTS (SELECT 1 FROM Table
by baudehlo 13y ago
For this I currently use:
UPDATE Table SET ... WHERE id=$1
if (rows_updated == 0) {
INSERT INTO Table ... WHERE NOT EXISTS (SELECT 1 FROM Table WHERE id=$1)
if (rows_inserted == 0) {
throw "Conflict!"
}
}
It's a bit of a hack, but works well enough. I agree would be nice to have a more transparent way of doing it.
- ocharles 13y agoThis is very susceptible to race conditions, which is why many of us want true UPSERT semantics. http://www.postgresql.org/docs/current/static/plpgsql-control-structures.html#PLPGSQL-UPSERT-EXAMPLE http://www.postgresql.org/docs/current/static/plpgsql-contro... is the current best way to do UPSERT in PG.
- epo 13y agoSo if there is a way to do UPSERT what is the problem? Are people just complaining about the lack of syntactic sugar?
- masklinn 13y ago> what is the problem? Quoting ocharles: > susceptible to race conditions, which is why many of us want true UPSERT semantics The snippet provided in the postgres doc is the current best, but it's still has a number of flaws: > This coding assumes the unique_violation error is caused by the INSERT, and not by, say, an INSERT in a trigger function on the table. It might also misbehave if there is more than one unique index on the table, since it will retry the operation regardless of which index caused the error. More safety could be had by using the features discussed next to check that the trapped error was the one expected.