node-orm-transaction icon indicating copy to clipboard operation
node-orm-transaction copied to clipboard

Help with transactions plugin!

Open gtsui opened this issue 12 years ago • 2 comments

Hi,

I am having issues with implementing the transactions plugin together with postgresql orm. I've tried two different implementations, one which follows the official documentation, which seems to have async issues, and the other using an async loop. Both are broken, where some rows are saved and some are not, and not in a predictable manner. Here is my code:

var myFunction = function(rows){
  db.transaction(function(err, txn){
    var total = rows.length;
    var myLoop = function(){
      if(total !== 0){
        var row = rows.pop();
        row.property = 'changed';
        row.save(function(err){
          if(err){ return console.log(err); }
          total -= 1;
          myLoop();
        });
      }else{
        txn.commit(function(err){
          if(err){ return console.log(err); }
        }  
     }
   }
}
var myFunction = function(row){
  db.transaction(function(err, txn){
    for(var i=0; i<rows.length; i++){
      rows[i].property = 'changed';
      rows[i].save(function(err){
        if(err){ console.log(err); }
      });
    }
    txn.commit(function(err){
      if(err){ return console.log(err) };
    });
  });

The documentation for the transaction plugin is a bit sparse, so if someone can help me understand how to use it properly, I would be very grateful. Thanks!

gtsui avatar Jan 02 '14 14:01 gtsui

Did u resolve this?

shredding avatar Jan 07 '18 10:01 shredding

For what it's worth - if you are using postgres and are committed to use it you could do something along the lines of:

MyModel.withinTransaction = async (func) => {
    await db.driver.db.query('BEGIN')
    try {
      const result = await func()
      await db.driver.db.query('COMMIT')
      return result
    } catch (e) {
      await db.driver.db.query('ROLLBACK')
      throw e
    }
  }

// in your methods:
methods: {
    
      doSomethingWithTransaction: async function (targetAccount, amount) {
       
        return await Account.withinTransaction(async () => {
              // everything in here is transaction save.
        })
      },
// go on

You can then deinstall node-orm-transaction

shredding avatar Jan 07 '18 14:01 shredding