我为两个钱包之间的资金转移创建了以下程序:
create or replace procedure transfer(
sender int,receiver int,amount bigint
)
language plpgsql
as $$
DeclARE balance_var INT DEFAULT 0;
BEGIN
select balance
into balance_var
from public.wallets
where id = sender for update;
IF balance_var < amount THEN
raise exception 'account has no enough balance: %',balance_var;
end if;
-- creating a transaction for sender
insert into transactions (amount,source_id,destination_id,description,status,trx_type)
values (-amount,sender,receiver,'transfer','COMPLETED','transfer');
-- creating a transaction for receiver
insert into transactions (amount,trx_type)
values (amount,'transfer');
-- subtracting the amount from the sender's account
update wallets
set balance = balance - amount
where id = sender;
-- adding the amount to the receiver's account
update wallets
set balance = balance + amount
where id = receiver;
COMMIT;
END;$$
我有三个问题:
- 在查看余额之前是否需要锁定第二个帐户?
- 使用此程序时可能会出现哪些问题?
- 哪个更有优势:在应用程序级别编写过程或编写查询(例如:使用 Hibernate)