我想知道是否有可能運行一系列的SQL語句,並讓它們都在單個事務中提交。nodejs pg沒有嵌套的交易
我正在看的場景是數組有一系列我希望插入到表中的值,而不是單獨地作爲一個單位。
我在看下面的項目,它提供了一個使用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);
}
,因爲我發現這使得很容易:https://www.npmjs.com/package/pg-transaction – Dercni
[PG-承諾(https://開頭的github .com/vitaly-t/pg-promise)爲交易提供了最好的支持,包括嵌套的(又名保存點)。查看[交易](https://github.com/vitaly-t/pg-promise#transactions)。而'pg-transaction'今天已經過時了) –