I am inserting a row in two different tables depending upon a condition.
Let say, we have table named stories with 2 fields under consideration:
(story_id and comments_count)
and 2 other tables:
regcomments (comment_id, story_id, comment_text)unregcomments (comment_id, story_id, comment_text)
Now, before inserting any new comment for any story_id, I just want to check if comments_count is less than 100. If so, the row should be inserted into regcomments, otherwise, the row should be inserted into unregcomments.
Here is the pseudo-code of how I’ve done that:
select comments_count from stories where story_id = x
if comment_count<100
insert into regcomments
else
insert into unregcomments
Now all what I am concerned about is if multiple users are accessing this script, Is there any chance this will fail? For example a story has 99 comments. 2 users call this function exactly at the same time. The first select query executes at the same time for both, and they both get 99. so both inserts will be made to regcomments, making count of regcomments 101, which is against my business rule. Any one has any idea, how the thing go. Or any ideas about how should I handle this scenario. (Don’t ask me why I am using 2 tables 😛 anyway)
Yes, it can/will fail because 10 request may all receive 99 comments_count from the SQL query, and each time new row will be inserted to regcomments, and then you’ll have 109 rows in the table.
One possible solution would be to move the checking logic into the SQL (use stored procedure with locking/mutex).