删除前PostgreSQL锁定行?

时间:2016-02-04 10:17:25

标签: sql postgresql transactions

我在postgresql中有一个事务,我执行以下命令:

  1. SELECT "amount", "accountId" from "transactions" where "id" = "123"
  2. DELETE from "transactions" where "id" = "123"
  3. UPDATE "accounts" set "balance" = "balance" - amountFetchedInCommand1 where "id" = accountFetchedInCommand1
  4. 现在我需要确保在命令1和2之间从transactions获取的行没有被修改(特别是其amountaccountId字段。

    我是否可以使用SELECT FOR UPDATE语句来锁定在命令1处获取的行,即使我不会更新行但只删除它?

    否则,确保此操作始终正确运行的最佳方法是什么?

    transactions.accountId是与account.id ON DELETE CASCADE相关联的外键

2 个答案:

答案 0 :(得分:2)

您可以在一个声明中执行第2步和第3步:

with deleted as (
   DELETE from transactions 
   where id = 123
   return amount, "accountId"
)
UPDATE accounts 
   set balance = accounts.balance - d.amount 
from deleted d
where accounts.id = d."accountId";

答案 1 :(得分:-1)

使用开始; //代码提交;

或开始交易[参数] //代码Comit;

更多文档:http://www.postgresql.org/docs/9.1/static/sql-start-transaction.html