Skip to content

Instantly share code, notes, and snippets.

@chowey
Created March 28, 2012 13:46
Show Gist options
  • Save chowey/2226296 to your computer and use it in GitHub Desktop.
Save chowey/2226296 to your computer and use it in GitHub Desktop.
pg atomic transaction test 2
var pg = require('pg'),
path = require('path'),
Query = require(path.join(path.dirname(require.resolve('pg')), 'query'));
pg.Client.prototype.next = function (config, values, callback) {
//can take in strings or config objects
config = (typeof(config) == 'string') ? { text: config } : config;
if (this.binary && !('binary' in config)) {
config.binary = true;
}
if(values) {
if(typeof values === 'function') {
callback = values;
} else {
config.values = values;
}
}
config.callback = callback;
var query = new Query(config);
this.queryQueue.unshift(query);
this._pulseQueryQueue();
return query;
};
var client = new pg.Client('pg://user:[email protected]/postgres');
client.connect(function () {
client.query('CREATE TEMP TABLE foo (bar real)', function () {
for (var i = 0; i < 5; i++)
insertRandomNumber();
});
client.once('drain', function () {
client.query('SELECT bar FROM foo', function (err, results) {
for (var i = 0; i < results.rowCount; i++)
console.log(results.rows[i].bar);
});
client.once('drain', client.end.bind(client));
});
});
function insertRandomNumber() {
console.log('BEGIN');
client.query('BEGIN', function () {
console.log('INSERT');
client.next('INSERT INTO foo VALUES (random()) RETURNING bar', function (err, result) {
if (result.rows[0].bar < 0.5)
console.log('COMMIT'), client.next('COMMIT');
else
console.log('ROLLBACK'), client.next('ROLLBACK');
});
});
}
@chowey
Copy link
Author

chowey commented Mar 28, 2012

Outputs the expected:

c:\node>node transact2
BEGIN
BEGIN
BEGIN
BEGIN
BEGIN
INSERT
COMMIT
INSERT
COMMIT
INSERT
ROLLBACK
INSERT
COMMIT
INSERT
COMMIT
0.0438101
0.187328
0.403612
0.16835

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment