Created
March 28, 2012 13:17
-
-
Save chowey/2226114 to your computer and use it in GitHub Desktop.
pg atomic transaction test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var pg = require('pg'); | |
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.query('INSERT INTO foo VALUES (random()) RETURNING bar', function (err, result) { | |
if (result.rows[0].bar < 0.5) | |
console.log('COMMIT'), client.query('COMMIT'); | |
else | |
console.log('ROLLBACK'), client.query('ROLLBACK'); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results in: