Reputation: 2506
I've been trying to write some database queries that run on node js, and this came up to my mind. I can smell I'm misunderstanding something, but can't figure it out what it is.
If node is single-threaded, then this means all function calls run one after another. If there are multiple clients accessing the same node server, there will still be a race in which request gets queued first, but as long as each request is processed one by one, doesn't this make all database operations performed in a single request atomic?
For example, let's say I want to 1) count the number of columns matching some value in a table and 2) insert a new row if the number is more than 10. (It is probably possible to do this in one SQL query, but let's assume I run them separately. It's a dumb example, but I hope you get the point.) I'd use a transaction to make sure the number of matching columns do not change unexpectedly. Now, I'm thinking to write a function that runs the two queries without a transaction. Would that guarantee to work properly on node?
Upvotes: 0
Views: 484
Reputation: 50568
I suppose you want to run your first call, a count, then you want to execute an insert in the callback of the previous call.
Because of the nature of js and thus of nodejs, once you are waiting for the response to the first call, once it is come back and put on the event loop (so, the count is gone, you already have the result on the fly), while waiting to be served, everything else can happen... Even another insert somewhere else could be served, why not (let me say, you are serving user requests, so an insert due to a request of another user, not the one that is executing the count).
That said, the insert of the second user could be served before the one sent after the count of the first user and that means that the insert bound to the count is working on a wrong expected size of the dataset.
That's only one of the possible cases you can incur in, but it should be enough to solve your doubts.
Upvotes: 1