I didn't know how to word this scenario in the title properly, so I apologize.
More specifically, this is a question I have regarding the asynchronous nature of Node.js (I'm still used to PHP).
Let's say a user is trying to register for an account and, prior to inserting the user, the system checks the database to make sure that his username is unique.
var checkUsernameAvailability = function (username, done) {
someDBImplementation.query('SELECT COUNT(username) FROM users WHERE username = ' + username, function (result) {
done(!!result);
});
};
var insertUser = function (username, password) {
checkUsernameAvailability(username, function (is_available) {
if (is_available) {
someDBImplementation.query('INSERT INTO users (...) ...');
} else {
// tell the user to pick a unique username
}
});
};
Let's say two users enter the username john at roughly the same time, while john is currently not in the database.
The first call to checkUsernameAvailability returns that the username is indeed available, so the INSERT operation begins.
However, the second call to checkUsernameAvailability is faster than the INSERT operation, therefore the second user also passes the availability test and the INSERT operation starts.
Whichever INSERT finishes first (presumably the first user's), by the time the second operation gets executed, it will throw some database error.
I know this is a poor example -- most database systems have a unique constraint built into them to check and handle at the time the operation is run. Still, is there a system in place to maintain the order in which queries are executed? Can I maintain that, if two separate clients make calls to a server, that the second SELECT query will wait until the first INSERT query is done?
Aucun commentaire:
Enregistrer un commentaire