删除前的PostgreSQL锁定行?

PostgreSQL lock row before delete?

我在 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

现在我需要确保在命令 1 和命令 2 之间,从 transactions 获取的行不会被修改(尤其是它的 amountaccountId 字段)。

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

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

transactions.accountId 是链接到 account.idON DELETE CASCADE 的外键)

您可以在一条语句中执行第 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";

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

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

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