CodeFoodPixels / node-promise-mysql

A wrapper for mysqljs/mysql that wraps function calls with Bluebird promises.
MIT License
338 stars 63 forks source link

Transaction support #91

Closed jesdynf closed 6 years ago

jesdynf commented 6 years ago

Do you have an example case of this being used with a multiple-query transaction?

Thanks!

CodeFoodPixels commented 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();
});
jesdynf commented 6 years ago

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();
    })
}
tirolel commented 6 years ago

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?

CodeFoodPixels commented 6 years ago

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();
})
tirolel commented 6 years ago

Great, thank you for quick response!