Skip to content

Instantly share code, notes, and snippets.

@prestonp
Last active August 29, 2015 14:03
Show Gist options
  • Save prestonp/c142f5642cecdf2cef14 to your computer and use it in GitHub Desktop.
Save prestonp/c142f5642cecdf2cef14 to your computer and use it in GitHub Desktop.
transaction example

Transactions API

To perform transactions use the dirac.tx api. Dirac defaults to using client pooling per request. So a single client must be used over the lifespan of a transaction. The tx will fetch one for you and release it upon .commit().

A dirac tx object has access to the same DALs in addition to transactional commands.

dirac.tx.create()

Creates a new tx object

tx.begin( [callback] )

Issues BEGIN

tx.rollback( [callback] )

Issues ROLLBACK

tx.commit( [ callback ] )

Issues COMMIT and releases the client. Subsequent calls on tx will throw an error.

it ('should perform transaction', function( done ){
// Grab a tx client which is used to issue subsequent queries
var tx = dirac.tx.create();
// The tx has access to the DALs but uses the tx client instead of
// the typical client pool
tx.begin(function(err) {
if (err) return tx.rollback();
tx.users.insert({ name: 'red fish' }, function(err) {
if (err) return tx.rollback();
tx.users.insert({ name: 'blue fish' }, function(err) {
if (err) return tx.rollback();
// End transaction and release client
tx.commit( done );
});
});
});
});
it ( 'should perform transaction async', function( done ) {
// This proposed transaction api aims to abstract client management,
// not control flow. This leave a simple api that the user can use
// with their choice of control flow library or just straight up
// callback style.
var tx = dirac.tx.create();
var async = utils.async;
async.series([
tx.begin.bind(tx)
, tx.users.insert.bind(tx, { name: 'red fish' })
, tx.users.insert.bind(tx, { name: 'blue fish' })
], function(err, results) {
assert(!err);
if ( err ) return tx.rollback();
tx.commit(done);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment