Version 3 (modified by 3 days ago) ( diff ) | ,
---|
Оптимизиран SQL-код, кој работи поедноставно и побрзо
DDL код
create table account( id serial primary key, username varchar(255) not null, email varchar(255) not null, password varchar(255) not null, balance decimal(15, 2) not null ); create table "transaction"( id serial primary key, amount decimal(15, 2) not null, currency varchar(255) not null, type varchar(50) not null, timestamp timestamp default current_timestamp, account_id int not null, foreign key (account_id) references account(id) ); create table transfer( id serial primary key, s_id int not null, r_id int not null, foreign key(s_id) references account(id), foreign key(r_id) references account(id) ); create table deposit( id serial primary key, account_id int not null, transaction_id int not null, amount decimal(15,2) not null, foreign key(account_id) references account(id), foreign key(transaction_id) references transaction(id) ); create table withdraw( id serial primary key, account_id int not null, transaction_id int not null, amount decimal(15,2) not null, foreign key(account_id) references account(id), foreign key(transaction_id) references transaction(id) ); create table transferred_money( id serial primary key, s_account_id int not null, r_account_id int not null, t_id int not null, currency varchar(50) not null, foreign key (s_account_id) references account(id), foreign key (r_account_id) references account(id), foreign key (t_id) references transaction(id) );
Trigger 2
CREATE OR REPLACE FUNCTION after_transaction_trigger2() RETURNS TRIGGER AS $$ BEGIN IF NEW.type = 'Deposit' THEN -- Log deposit as a self-transfer INSERT INTO transfer(s_id, r_id) VALUES (NEW.account_id, NEW.account_id); ELSIF NEW.type = 'Withdrawal' THEN -- Log withdrawal as a self-transfer INSERT INTO transfer(s_id, r_id) VALUES (NEW.account_id, NEW.account_id); ELSIF NEW.type LIKE '(MKD) Transfer Out to%' OR NEW.type LIKE '(USD) Transfer Out to%' OR NEW.type LIKE '(EUR) Transfer Out to%' OR NEW.type LIKE '(GBP) Transfer Out to%' THEN -- Extract recipient username and insert into transfer table INSERT INTO transfer(s_id, r_id) SELECT NEW.account_id, (SELECT id FROM account WHERE username = TRIM(SUBSTRING(NEW.type FROM POSITION('Transfer Out to ' IN NEW.type) + 15)) LIMIT 1); END IF; RETURN NEW; END; $$ LANGUAGE plpgsql; CREATE TRIGGER after_transaction2 AFTER INSERT ON transaction FOR EACH ROW EXECUTE FUNCTION after_transaction_trigger2();
Note:
See TracWiki
for help on using the wiki.