插入交易并更新帐户平衡

我为两个钱包之间的资金转移创建了以下程序:

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;$$

我有三个问题:

  1. 在查看余额之前是否需要锁定第二个帐户?
  2. 使用此程序时可能会出现哪些问题?
  3. 哪个更有优势:在应用程序级别编写过程或编写查询(例如:使用 Hibernate)
azsxdcf951357 回答:插入交易并更新帐户平衡

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/1175.html

大家都在问