Create table account
drop table if exists accounts;
create table accounts (
id int generated by default as identity,
name varchar(100) not null,
balance dec(15,2) not null,
primary key(id)
);
insert into accounts(name,balance) values('Bob',10000);
insert into accounts(name,balance) values('Alice',10000);
Create store procedure for update balance :
create or replace procedure sp_transfer (sender int, recever int, amount int)
language plpgsql
as
$$
begin
update accounts set balance = balance - amount where id=sender ;
update accounts set balance = balance + amount where id=recever ;
commit;
end
$$
Create function for update balance :
create or replace function fn_transfer()
returns trigger
language plpgsql
as
$$
begin
if new.balance<>old.balance then
insert into amount_audit(cust_id,c_name,t_amount,balance,datetime,status)
values (old.id,old.name,new.balance - old.balance,new.balance,current_timestamp,
CASE WHEN new.balance - old.balance > 0 then 'Cradit' else 'Debit' end );
end if;
return new;
end
$$
Create trigger
create trigger tg_transfer
before update
on accounts
for each row
execute procedure fn_transfer()
Nice guide on setting up triggers and procedures for account transfers in Postgres. The way you log every debit and credit with a trigger is super handy for auditing. Gonna try this in my test DB and see how it works. Also found some extra resources while reading, check kolkata ff if anyone wants quick reference links.
ReplyDelete