Select unlocked row in Postgresql

后端 未结 14 2116
你的背包
你的背包 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.

提交回复
热议问题