Select unlocked row in Postgresql

后端 未结 14 2057
你的背包
你的背包 2020-12-13 06:20

Is there a way to select rows in Postgresql that aren\'t locked? I have a multi-threaded app that will do:

Select... order by id desc limit 1 for update


        
相关标签:
14条回答
  • 2020-12-13 06:53

    ^^ that works. consider having an "immediate" status of "locked".

    Let's say your table is like that:

    id | name | surname | status

    And possible statuses for example are: 1=pending, 2=locked, 3=processed, 4=fail, 5=rejected

    Every new record gets inserted with status pending(1)

    Your program does: "update mytable set status = 2 where id = (select id from mytable where name like '%John%' and status = 1 limit 1) returning id, name, surname"

    Then your program does its thing and if it cames up with the conclusion that this thread shouldn't had processed that row at all, it does: "update mytable set status = 1 where id = ?"

    Otherside it updates to the other statuses.

    0 讨论(0)
  • 2020-12-13 06:54

    How about the following? It might be treated more atomically than the other examples but should still be tested to make sure my assumptions aren't wrong.

    UPDATE users SET flags = 1 WHERE id = ( SELECT id FROM users WHERE flags = 0 ORDER BY id DESC LIMIT 1 ) RETURNING ...;
    

    You'll probably still be stuck with whatever locking scheme postgres uses internally to supply consistent SELECT results in the face of a simultaneous UPDATEs.

    0 讨论(0)
提交回复
热议问题