MySQL Insertion: Race condition

萝らか妹 提交于 2019-12-12 03:17:40

问题


I would like to know if there is a real case scenario in which race condition problems can actually occur on an insertion query. So I have a table "User" with the following fields:

User:
iduser | idcompany | name | email

I use a composite primary key for this table that is (iduser, idcompany). None of these fields is set to AUTO_INCREMENT. I get the value of the field "idcompany" through a session variable, so there's is not a real problem in this. However, I use a getNextUserId() function to get the next valid iduser value through a select query like this:

SELECT MAX(iduser) + 1 AS next_iduser FROM User WHERE idcompany = {myCompanyId};

I wonder if there is any case in which a duplicate combination of (iduser, idcompany) could be inserted in the database because of race condition and if so how is this scenario possible. Doesn't MySQL lock the table on insertion? Wouldn't a duplicate combination of (iduser, idcompany) simple be rejected or I could really have a duplicate primary key in my table? I am aware of strategies to totally prevent race condition like using AUTO_INCREMENT primary key, using SQL transactions or manually lock the "User" table but I would like to understand the mechanism behind a possible race condition in this case and what are the real problems in this implementation. Right now, none of these fields is required to be unique in my table for obvious reasons, but I would like to know if a UNIQUE constraint on iduser for example would alter the scenario I am facing and why does this happen.


回答1:


You wrote you had a composite primary key on iduser, idcompany fields. This constraint will prevent the table from having duplicate iduser, idcompany pairs. The worst that could happen without locking is that the a creation of a user will be prevented by the violation of the primary key.



来源:https://stackoverflow.com/questions/38998297/mysql-insertion-race-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!