免責聲明

Disclaimer (免責聲明)
繼續閱覽代表您接受以上的免責聲明.
To continue reading means you accept the above disclaimer.

2015年6月24日 星期三

mysql consecutive inserts on one connection lead to race?


http://stackoverflow.com/questions/19283825/mysql-transactions-not-stopping-race-conditions-from-for-loop

select ... for update to prevent race condition ?

"""...
var testTransaction = function (count) {
connection.beginTransaction(function(err) {
if (err) throw err;
db.query('SELECT * FROM myTable WHERE id = 1 FOR UPDATE', function(err, rows, result) {
if (err) {
connection.rollback(function() {
throw err;
});
}
connection.query('UPDATE myTable SET myField=? WHERE id=1', (count + 1), function(err, result) {
if (err) {
db.rollback(function() {

...
}

for (var i = 0; i < 2; i++) { testTransaction(i); } ...""" 



//===================================
--> uses a different connection for each transaction.

function conn() {
var connection = mysql.createConnection({
host : 'localhost',
user : 'user',
password : 'pass',
database : 'test'
});
return connection;
}

for (var i = 0; i < 2; i++) { testTransaction(conn(),i); } 



--> or promise pattern
transaction1.then(transaction2);


沒有留言:

張貼留言