Skip to content

Instantly share code, notes, and snippets.

@samholmes
Created March 15, 2012 18:47
Show Gist options
  • Save samholmes/2045969 to your computer and use it in GitHub Desktop.
Save samholmes/2045969 to your computer and use it in GitHub Desktop.
Shows issue using transactions on the same db connection
var http = require('http');
var mysql = require('mysql');
var db = mysql.createClient({
user: 'root',
password: 'password',
database: 'db1'
});
db.query("BEGIN"); // Start first transaction
db.query("INSERT test (val) VALUES ('foo')"); // Do stuff in transaction
// Wait 10 seconds
setTimeout(function(){
db.query("ROLLBACK"); // End transaction cancelling all changes with a rollback
console.log('ROLLBACK first transaction');
}, 10000);
http.createServer(function (req, res) {
if (req.url == '/')
{
var db = mysql.createClient({
user: 'root',
password: 'password',
database: 'db1'
});
db.query("BEGIN"); // Start new transaction
db.query("INSERT test (val) VALUES ('bar')"); // Do stuff
db.query("COMMIT"); // Commit changes
// Select all data from test table. It should only show the 'bar' record.
db.query("SELECT * FROM test", function(err, results, fields) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(JSON.stringify(results));
});
}
}).listen(3000, 'localhost');
delimiter $$
CREATE TABLE `test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`val` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=latin1$$
@samholmes
Copy link
Author

The issue with the code now is that http.createServer's callback function get's called twice per request sometimes. This is causing two records to be inserted per request. How do I prevent this from happening?

@samholmes
Copy link
Author

Multiple request problem had to do with /favicon.ico being requested after page request.

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