일련의 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'은 오늘 쓸모가 없습니다.) –