没有嵌套的nodejs pg事务

我想知道是否有可能运行一系列的SQL语句,并使它们都在单个事务中提交。

我正在看的场景是一个数组有一系列的值,我想插入到一个表中,而不是单独的,但作为一个单位。

我正在看下面的项目,它提供了使用pg的节点中事务的框架。 单个事务看起来是嵌套在一起的,所以我不确定这是如何处理一个包含可变数目元素的数组的。

https://github.com/brianc/node-postgres/wiki/Transactions

var pg = require('pg'); var rollback = function(client, done) { client.query('ROLLBACK', function(err) { //if there was a problem rolling back the query //something is seriously messed up. Return the error //to the done function to close & remove this client from //the pool. If you leave a client in the pool with an unaborted //transaction weird, hard to diagnose problems might happen. return done(err); }); }; pg.connect(function(err, client, done) { if(err) throw err; client.query('BEGIN', function(err) { if(err) return rollback(client, done); //as long as we do not call the `done` callback we can do //whatever we want...the client is ours until we call `done` //on the flip side, if you do call `done` before either COMMIT or ROLLBACK //what you are doing is returning a client back to the pool while it //is in the middle of a transaction. //Returning a client while its in the middle of a transaction //will lead to weird & hard to diagnose errors. process.nextTick(function() { var text = 'INSERT INTO account(money) VALUES($1) WHERE id = $2'; client.query(text, [100, 1], function(err) { if(err) return rollback(client, done); client.query(text, [-100, 2], function(err) { if(err) return rollback(client, done); client.query('COMMIT', done); }); }); }); }); }); 

我的数组逻辑是:

 banking.forEach(function(batch){ client.query(text, [batch.amount, batch.id], function(err, result); } 

pg-promise为交易提供了非常灵活的支持。 查看交易 。

它也支持部分嵌套事务,即保存点。

这个库自动实现事务处理,这些是现在应该使用的事情,因为如果您尝试像在示例中那样手动组织事务,则事情太多会出错。

看到一个相关的问题: 在事务中可选的INSERT语句