dresende / node-orm2

Object Relational Mapping
http://github.com/dresende/node-orm2
MIT License
3.07k stars 376 forks source link

Help with transactions plugin! #419

Open gtsui opened 10 years ago

gtsui commented 10 years ago

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:

1)

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); }
        }  
      }
    }
}

2)

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!

xaguzman commented 10 years ago

Yesterday we were fighting this problem. In our case however it was mysql. Mysql was ignoring the transaction due to the autocommit.

Setting it trough SET autocommit = 0 didn't work.

We had to explicitly do this in mysql configuration file:

[mysqld] autocommit = 0