我在postgresql中有一个事务,我执行以下命令:
SELECT "amount", "accountId" from "transactions" where "id" = "123"
DELETE from "transactions" where "id" = "123"
UPDATE "accounts" set "balance" = "balance" - amountFetchedInCommand1 where "id" = accountFetchedInCommand1
现在我需要确保在命令1和2之间从transactions
获取的行没有被修改(特别是其amount
和accountId
字段。
我是否可以使用SELECT FOR UPDATE
语句来锁定在命令1处获取的行,即使我不会更新行但只删除它?
否则,确保此操作始终正确运行的最佳方法是什么?
(transactions.accountId
是与account.id
ON DELETE CASCADE
相关联的外键
答案 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