Suppose I have a function which is used to increment a column called project_id by 1 in the database under certain circumstances. (Assume auto increment will not satisfy this use case, due to logic that has to be run before determining whether to increment).
When a user clicks "New Project", the function finds the current largest project_id in the database, does SOME OTHER STUFF, and adds a row by incrementing project_id by 1.
Is there a possibility that when multiple users connect, the time that the server takes to process SOME OTHER STUFF, causes multiple users to pick up the same project_id? If so, how would you go about avoiding this problem? Is it just a bad idea to increment in this way?
Here is an illustration. This example is based on Laravel, but the question applies generally.
function ReallyLongFunction () {
//figure out what the current max project_id is and increment by 1
$newProjectId = Project::max("project_id")+1;
//Some other stuff that the server has to do. I am exaggerating here the length of time.
//If another user triggers this function, will both users will have the same project id?
sleep(2);
//Insert new row into database
$project = new TempProject;
$project->project_id = $newProjectId;
$project->save();
}