-- apply appropriate locks to ... create or replace function transfer(N integer, Src text, Dest text) returns integer declare sID integer; dID integer; avail integer; begin -- LOCK TABLE Accounts IN SHARE UPDATE EXCLUSIVE MODE; -- select id,balance into sID,avail from Accounts where name=Src for update; if (sID is null) then raise exception 'Invalid source account %',Src; end if; select id into dID from Accounts where name=Dest for update; if (dID is null) then raise exception 'Invalid dest account %',Dest; end if; if (avail < N) then raise exception 'Insufficient funds in %',Src; end if; -- total funds in system = NNNN update Accounts set balance = balance-N where id = sID; -- funds temporarily "lost" from system update Accounts set balance = balance+N where id = dID; -- funds restored to system; total funds = NNNN -- COMMIT; -- return nextval('tx_id_seq'); end;