加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

perl – 如何在使用DBIx :: Class :: ResultSet的find_or_create

发布时间:2020-12-16 06:26:03 所属栏目:大数据 来源:网络整理
导读:从 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 h
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.

如果您没有很多并发性,那么您也可以忽略该问题.时间段非常小,所以实际上很少发生.如果您发现重复的密钥违规错误,这不会造成任何伤害,那么您也已经涵盖了这一点.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读