开发者

PostgreSQL and locking

Hopefully some smarter DBAs than I can help me find a good solution for what I need to do.

For the sake of discussion, lets assume I have a table called 'work' with some number of columns, one of which is a column that represents ownership of that row of work from a given client. The scenario is that I'll have 2 clients connected and polling a table for work to be done, when a row (or some number of rows) shows up, the first client that selects the rows will also update them to imply ownership, that update will remove those rows from being returned to any other client's selects. 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 bein开发者_开发知识库g returned the same rows via the select?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜