PostgreSQL and locking

你离开我真会死。 提交于 2019-12-01 01:02:15
Ketema

The UPDATE statement with RETURNING clause is the way to do this.

UPDATE table
SET ownership = owner
RETURNING ( column list );

REFERENCES:

Similar Question

Documentation

My question is, in this scenario, what sort of locking can I use to prevent 2 clients from hitting the table at the same time and both of them being returned the same rows via the select?

No locking needed here.

In the UPDATE, simply specify that you only want the script to take ownership of the task if the owner is still null (assuming that's how you flag unassigned tasks). This should work:

UPDATE foo SET owner = ? WHERE id = ? AND owner = ? WHERE owner IS NULL

If the number of modified rows is equal to the number you expected (or a RETURNING clause returns results as suggested by @Ketema), then you successfully grabbed ownership.


Fake edit because I noticed your comment mere moments before submitting this answer:

eg: 2 clients issuing that query at the same time, they have no chance of manipulating the same rows?

Correct. You might want to read up on MVCC. Running these statements outside of a transaction will do the right thing. Behavior inside a transaction will be different.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!