Select unlocked row in Postgresql

后端 未结 14 2120
你的背包
你的背包 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:38

    My solution is to use the UPDATE statement with the RETURNING clause.

    Users
    
    -----------------------------------
    ID        | Name       |      flags
    -----------------------------------
    1         |  bob       |        0  
    2         |  fred      |        1  
    3         |  tom       |        0   
    4         |  ed        |        0   
    

    Instead of SELECT .. FOR UPDATE use

    BEGIN; 
    
    UPDATE "Users"
    SET ...
    WHERE ...;
    RETURNING ( column list );
    
    COMMIT;
    

    Because the UPDATE statement obtains a ROW EXCLUSIVE lock on the table its updating you get serialized updates. Reads are still allowed, but they only see data before the start of the UPDATE transaction.

    Reference: Concurrency Control Chapter of Pg docs.

提交回复
热议问题