Closed jesdynf closed 6 years ago
var mysql = require('promise-mysql');
var connection;
mysql.createConnection({
host: 'localhost',
user: 'sauron',
password: 'theonetruering',
database: 'mordor'
}).then(function(conn){
connection = conn;
return connection.beginTransaction();
}).then(function(){
return connection.query('INSERT INTO log SET data=?', 'badger');
}).then(function(){
return connection.query('INSERT INTO food SET data=?', 'cheese');
}).then(function() {
return connection.commit();
}).catch(function(){
return connection.rollback();
});
Thanks a ton! I ended up with this pattern:
function transactionPoolTest(pool) {
let connection;
return pool.getConnection()
.then(function(conn){
connection=conn;
return connection.beginTransaction();
}).then(function(){
return connection.query('SELECT NOW()');
}).then(function(){
return connection.query('SELECT NOW()');
}).then(function(r){
return connection.commit().then(() => r);
}).catch(function(err){
return connection.rollback()
.then(() => Promise.reject(err));
}).finally(function(){
return connection.release();
})
}
Important note: don't forget to call connection.end() when you're finished otherwise the Node process won't finish
Thanks a lot for the example. But where do we call the end() of connection as mentioned?
At some point after you've done the rollback/commit.
In the case of the above example being all that's happening, it'd be like this:
var mysql = require('promise-mysql');
var connection;
mysql.createConnection({
host: 'localhost',
user: 'sauron',
password: 'theonetruering',
database: 'mordor'
}).then(function(conn){
connection = conn;
return connection.beginTransaction();
}).then(function(){
return connection.query('INSERT INTO log SET data=?', 'badger');
}).then(function(){
return connection.query('INSERT INTO food SET data=?', 'cheese');
}).then(function() {
return connection.commit();
}).catch(function(){
return connection.rollback();
}).then(function(){
return connection.end();
})
Great, thank you for quick response!
Do you have an example case of this being used with a multiple-query transaction?
Thanks!