【发布时间】:2016-07-21 09:55:57
【问题描述】:
我想知道是否可以运行一系列 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);
}
【问题讨论】:
-
我发现这很容易:npmjs.com/package/pg-transaction
-
pg-promise 为事务提供了最好的支持,包括嵌套事务(又名保存点)。见Transactions。而
pg-transaction今天已经过时了;)
标签: node.js postgresql transactions