从
find_or_create
的文档:
Note: Because find_or_create() reads from the database and then
possibly inserts based on the result,this method is subject to a race
condition. Another process could create a record in the table after
the find has completed and before the create has started. To avoid
this problem,use find_or_create() inside a transaction.
仅仅在Postgresql中的事务中使用find_or_create()就足够了吗?
解决方法
不,文档不正确.仅使用事务并不能避免此问题.它只保证在发生异常时回滚整个事务 – 这样就不会将不一致的状态保存到数据库中.
要避免此问题,您必须锁定表 – 在事务内部,因为所有锁都在事务结束时释放.就像是:
BEGIN; LOCK TABLE mytbl IN SHARE MODE; -- do your find_or_create here COMMIT;
但这并不是治愈一切的神奇疗法.它可能会成为性能问题,并且可能存在死锁(并发事务相互试图锁定另一个已锁定的资源). Postgresql将检测到这种情况,并取消除一个竞争交易之外的所有交易.您必须准备好在失败时重试操作.
The PostgreSQL manual about locks.
如果您没有很多并发性,那么您也可以忽略该问题.时间段非常小,所以实际上很少发生.如果您发现重复的密钥违规错误,这不会造成任何伤害,那么您也已经涵盖了这一点.