ruby on rails 3 - First_or_create yet ERROR: duplicate key value violates unique constraint -
i have following code:
rating = user.recipe_ratings.where(:recipe_id => recipe.id).where(:delivery_id => delivery.id).first_or_create yet somehow occasional pg::error: error: duplicate key value violates unique constraint errors this. can't think of reason should happen, since whole point of first_or_create prevent those.
is crazy race-condition? how can solve without maddening series of begin...rescue blocks?
this seems stem typical race condition "select or insert" case.
ruby seems choose performance on safety in implementation. quoting "ruby on rails guides":
the
first_or_createmethod checks whether first returnsnilor not. if returnnil,createcalled....
the sql generated method looks this:
select * clients (clients.first_name = 'andy') limit 1 begin insert clients (created_at, first_name, locked, orders_count, updated_at) values ('2011-08-30 05:22:57', 'andy', 0, null, '2011-08-30 05:22:57') commit
if that's actual implementation (?), seems completely open race conditions. transaction can select between first transaction's select , insert. , try own insert, raise error reported, since first transaction has inserted row in meantime.
the time frame race condition drastically reduced data-modifying cte. safe version not cost more. guess have reasons.
compare safe implementation:
Comments
Post a Comment