Fixes bug 1032851 - add a retry if we get a duplicate on UPSERT

same comment as above, lift the retry into an outer scope.