3 ms·
This is an issue I've had with NodeJS recently. 1. Check for existence of row by a key in a Postgres table 2. If not present, create one You can have
by teaearlgraycold 5y ago
This is an issue I've had with NodeJS recently.
1. Check for existence of row by a key in a Postgres table
2. If not present, create one
You can have a race condition to 2. You could do the insertion itself as the check to avoid this issue. But regardless this is a race condition that you need to think about in async environments.
- e12e 5y agoTrue, this is why database libraries/orms can be dangerous - the "normal" db way is to wrap 1,2 in a transaction. Unfortunately, while transactions are often available many db interfaces lures the unwary programmer away from using transactions, because reading/writing the db "looks like" reading/writing a variable/object.
- djur 5y agoYou have to consider that in multiprocess scenarios as well, though. All forms of concurrency introduce that problem.
- hibbelig 5y agoThe same thing could happen with any other form of concurrency. In this case you could wrap the two statements in a transaction with the appropriate isolation level. Not sure what it is called — read consistent? Snapshot?