I am building an app on node.js using express, and node-mysql driver. There is a couple of cases in my app when I need to make a series of database inserts/updates. I want them in a transaction such that if the second or third one fails, the previous inserts are rolled back completely.
Currently, the way I am doing this is to have some kind of middleware which does a START TRANSACTION when a request arrives. During the course of processing of the request, if any error is thrown, I catch this error, and do a ROLLBACK. If no error occurs, I do a COMMIT before sending the response to the browser.
However, I am now concerned that this won’t work when multiple users access the application simultaneously, as MySQL does a forced commit if another request tries to begin it’s own transaction with START TRANSACTION! I am currently using only a single instance of node, and a single MySQL connection for all the requests.
Can someone please advice me if my concerns are valid, and how should I get in transactions support?
You’ll need to create a client pool, or somehow otherwise ensure that two different pages aren’t interspersing commands on the same connection (at least while any of them is in a transaction).
Since you want to conditionally do a rollback based upon the result of an earlier command, you’ll need to chain the db calls together through their callbacks and not rely on the node-mysql queuing behavior. That will open up a window for some other page to come in and queue up an operation on the same connection as you suggest.
You could create and manage your own queue, but that would end up serializing all transactional pages (assuming you’re sticking with the single connection model).
From a quick googling, it looks like there are several node-mysql pools on github. After looking at them, though, they don’t look like they’ll help with your issue.