brianc / node-pg-pool

A connection pool for node-postgres
MIT License
180 stars 64 forks source link

Question about transaction and client.release(err) #52

Closed 3n-mb closed 7 years ago

3n-mb commented 7 years ago

Context

To work with a transaction, we get client

let client = await pool.connect();

After we done, client.release() should be called. If we call client.release(err), client will be destroyed (or so it seems). Usual (non prepare-d) transaction is alive as long as postgres' session is alive. Session is associated with client connection.

Question

Can client.release(err) be used as a sure way to rollback? If so, it allows for simple pattern, without ever writing explicit rollback:

try {
   client.query('BEGIN');
   ....
   // throw if conditions are not met
   ....
   client.query('COMMIT');
   client.release();
} catch (err) {
   client.release(err);  // kills transaction with client's connection
   throw err;  // for dealing elsewhere
}

Of cause, this isn't for places were rollback conditions are common. 1) Can this be done? 2) Or, is it too heavy on resources even for infrequent rollbacks?

brianc commented 7 years ago

Yeah, you can definitely do rollbacks that way. The connection overhead is non-trivial so if you expect the transaction to need to be rolled back the majority of the time I'd use a ROLLBACK statement, but if it's infrequent or only unknown error conditions which might cause a query within the transaction to fail then calling client.release(err) is a good way to go.