Hello eveyone!
An upsert operation should perform an update if a record already
exists in the table,
or insert the same record into the table otherwise.
Up till now, I was using stored procedures for the job, one such as
this:
http://www.postgresql.org/docs/current/static/plpgsql-control-structures.html#PLPGSQL-UPSERT-EXAMPLE
From what I've gathered the best option would be to create a simple
retrying strategy, pseudo code ensues:
@tailrec
def upsert(row) =
try{
table.update(row)
if (updated) return
table.insert(row)
return
}
catch {
case DuplicatePrimaryKeyInsertFailure dpkif =>
// this should only happen if an insert occured right between
our update and insert statements
// keep retrying because the next one *should* pass as an update
upsert(row)
}
The main problem here is trying to identify the exception mentioned
above.
Should I use simple pattern matching to find out the error type or is
there a smarter way?
The underlying database is PostgreSQL 9, so I know the error messages
can vary depending on localization.
Of course, if there is alredy some smart atomic way of performing an
upsert that would be much better then reinventing the wheel.
Thanks,
Gordan Valjak