2016-07-21 3 views
2

일련의 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); 
} 
+0

난 이후이를 발견하게하는이 쉽다 : https://www.npmjs.com/package/pg-transaction – Dercni

+1

[PG-약속] (https : //로 GitHub의 .com/vitaly-t/pg-promise)는 중첩 된 트랜잭션 (예 : 세이브 포인트)을 포함하여 트랜잭션에 대한 최상의 지원을 제공합니다. [거래] (https://github.com/vitaly-t/pg-promise#transactions)를 참조하십시오. 그리고'pg-transaction'은 오늘 쓸모가 없습니다.) –

답변

1

pg-promise는 거래를위한 매우 유연한 지원을 제공합니다. Transactions을 참조하십시오.

또한 부분 중첩 트랜잭션 (일명 세이브 포인트)을 지원합니다.

예제에서와 같이 트랜잭션을 수동으로 구성하려고하면 라이브러리가 자동으로 트랜잭션을 구현합니다. 요즘 사용해야하는 것은 잘못 처리 될 수 있기 때문입니다.

이 관련 질문을 참조하십시오 : Optional INSERT statement in a transaction

+0

노드 진행과 함께 먼저 연결 풀을 설정 한 다음 연결을 사용하고 연결을 해제합니다. pgp가 이것을 자동으로 수행하고 PHP readme가 연결 풀을 참조합니까? – Dercni

+0

@ user1567212'pg-promise'는 어디에서나 문서에 언급 된대로 자동으로 연결을 관리합니다. –