I'm trying to get a Sails.js transaction, in which I update two different models, to work. The code I have right now is pretty big, but I'll try to shorten it. I'm also using promises.
I followed the example from here: http://ift.tt/1CYmhTf
Code:
// These vars are to set up a direct mySQL connection
var mySqlPath = process.env.PWD + '/node_modules/sails-mysql/node_modules/mysql';
var mysql = require(mySqlPath);
var sailsMySqlConfig = sails.config.connections.mysqlServer;
var con = mysql.createConnection({
host: sailsMySqlConfig.host,
user: sailsMySqlConfig.user,
password: sailsMySqlConfig.password,
database: sailsMySqlConfig.database,
multipleStatements: true
});
// And then all the model updating promise
ModelOne.findOne({ id: req.param('id') })
.then(function(result) {
// Start the transaction
con.query("START TRANSACTION;");
})
.then(function(){
return ModelTwo.findOrCreate({
id: someNumber
}, {
id: someOtherNumber,
start: Date.now(),
});
})
.then(function() {
var eventQuery =
'CREATE EVENT IF NOT EXISTS test' + ' '
+ 'ON SCHEDULE AT FROM_UNIXTIME(UNIX_TIMESTAMP() + 100) '
+ 'DO '
+ 'UPDATE modeltwo SET status = "blah"'
+ 'WHERE id = ' + someNumber;
return ModelTwo.query(eventQuery);
})
.then(function() {
// Let's go to .catch()
throw new Error('Intentional error to test rollback');
return ModelOne.update({ id: project.id },
{
status: 'test'
});
})
.then(function() {
// The promise never reaches COMMIT
con.query("COMMIT;", function(err) {
if(err){ console.log(err)}
con.end(function(err) {
if (err) {
console.log(err)
}
console.log("done");
return res.view('home/index');
});
});
})
.catch(function(err){
// Rollback the changes
con.query("ROLLBACK;", function(err){
con.end(function() {
return res.serverError();
});
});
});
As you can see, I'm updating/creating two models, ModelOne and ModelTwo. I throw an error before finishing up everything, which should then make the Promise go into the rollback query, which in turn, should delete all changes made, because they weren't committed; however, it seems that the transaction isn't working at all, because I can see the changes being applied in the database, without being rolled back.
I can't figure out why. How can I do transactions with Sails.js?
By the way, I have checked the following links:
How to handle async concurrent requests correctly? - In here, it seems that the transaction is for only one model, plus wouldn't the answer in here fail because the queries are pooled?
Transactional SQL with Sails.js - Seems to be the same thing.
Thanks.
Aucun commentaire:
Enregistrer un commentaire