i'm facing an issue with my MySQL database and my RESTful API in NodeJS
I have a request that does this :
function plusOneToValue(id, callback) {
MySQLDatabase.pool.getConnection(function(err, connection) {
if (err) return callback(err)
connection.query("SELECT id, value, property FROM values WHERE id = ?",
[id], function(err, entries) {
if (err) {
connection.release();
return callback(err);
}
if (entries.length == 0) {
connection.release();
return callback("some error");
}
var entry = entries[0]
if (entry.property = true)
connection.query("UPDATE values SET value = ? WHERE id = ?",
[entry.value + 1, entry.id], function(err, users) {
connection.release();
if (err) return callback(err);
return callback();
});
else {
connection.release();
return callback();
}
});
});
}
My problem is that when i call this function 3 times at the same time, it has this behavior :
- SELECT
- SELECT
- SELECT
- UPDATE
- UPDATE
- UPDATE
When it should have :
- SELECT
- UPDATE
- SELECT
- UPDATE
- SELECT
- UPDATE
I've tried to fixed it with semaphores, but the thing is i don't want it to block at every call ! Only if there's a concurrential access to the row that has the id passed in parameter.
Does anyone know how i can achieve this ?