2016-07-21 11 views
2

一連のSQL文を実行し、それらをすべて1回のトランザクションでコミットできるかどうかを知りたいと思います。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)は、ネストされたトランザクション(セーブポイントとも呼ばれます)を含むトランザクションの最適なサポートを提供します。 [Transactions](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'はどこのドキュメントにも述べられているように自動的に接続を管理します。 –

関連する問題