We have a game where user can login and play a game, the game is for a group of 6 users only and when 6 users joins in a group the game starts.
we have a table in mysql named “temp_group” with user_id and a random_number Now, what we have to achieve is when a user enters the game we need to insert his user_id and check how many users are already in the group with same random_number, the scenario are as follows:
- If no user are there in the group (first User to enter the game) - we generate a random_number and insert it against the new user
- There are users in a group (2nd to 6th user joins the game) – fetch the random_number for that group and update it against this user
- If 7th user join the game - treat him as a new user for a group and do as in point No 1.
We have created a stored procedure where we first check
SELECT count(random_number), random_number from temp_group group by random_number HAVING COUNT(random_number) < 6 order by id ASC limit 1
If we get the row, we fetch the random_number and update it for the new user (2th – 6th User)
If we do not get the row, we generate the random_number and update it against the new user.
Our Stored Procedure:
BEGIN
DECLARE ch_done INT DEFAULT 0;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET ch_done = 1;
START TRANSACTION;
SELECT count(random_number), random_number from `temp_group` where group by random_number HAVING COUNT(random_number) < players order by temp_id ASC limit 1 into cnt, randomnumber;
IF(ch_done = 1) THEN
IF(randomnumber IS NULL) OR (cnt = 0) THEN
SET randomnumber = MD5(NOW());
SET cnt = 0;
END IF;
END IF;
INSERT INTO temp_group (`user_id`,`random_number`,`no_of_players`) VALUES(userid,,randomnumber,6) ON DUPLICATE KEY UPDATE `random_number` = randomnumber, `no_of_players` = 6;
COMMIT;
END
Problem:
When we tested with a single user joining the game at a time, it works proper. But when we tested it with concurrent connections, the same random_number is assigned to more then 6 users.
The Problem is when concurrent connections are calling the stored procedure, all the stored procedure fetches the select query and gets random_number and so it just updates the same random_number for all the users. Can anyone help me on how to stop the stored procedure from reading the data till the previous stored procedure updates the table and commit