Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- CREATE OR REPLACE FUNCTION trigf() RETURNS trigger AS
- $$
- DECLARE num_of_buys integer;
- BEGIN
- IF (TG_OP = 'INSERT') --checks if insert or update
- THEN
- num_of_buys := (select count(*) from buys where new.cid = cid AND new.rno = rno and new.iname = iname);
- IF num_of_buys >= 5 --do if client bought item 5 times, no matter the quantity
- THEN
- IF NOT EXISTS( select * from likes where new.iname = iname AND new.cid = cid)
- THEN --do if likes table doesn't have item yet
- INSERT INTO likes (cid,iname) values (new.cid, new.iname); -- insert the item and the related cid
- RETURN new;
- ELSE
- RAISE NOTICE 'client no. % likes % product ' , new.cid , new.iname;
- RETURN NULL;
- END IF;
- ELSE IF EXISTS( select * from likes where new.iname = iname AND new.cid = cid )
- THEN
- DELETE from likes where cid = new.cid AND iname = new.iname;
- RETURN new;
- ELSE IF (TG_OP = 'UPDATE') ----checks if insert or update
- THEN
- num_of_buys := (select count(*) from buys where new.cid = cid AND new.rno = rno AND new.iname);
- IF num_of_buys >= 5
- THEN
- IF NOT EXISTS( select * from likes where old.iname = iname AND old.cid = cid)
- THEN
- INSERT INTO likes (cid,iname) values (old.cid, old.iname);
- RETURN new;
- ELSE
- DELETE FROM likes where cid = old.cid AND iname = old.iname;
- INSERT INTO likes (cid,iname) values (new.cid, new.iname);
- RETURN new;
- END IF;
- ELSE
- IF EXISTS( select * from likes where old.iname = iname AND old.cid = cid )
- THEN
- DELETE from likes where cid = old.cid AND iname = old.iname;
- RETURN new;
- END IF;
- END IF;
- END IF;
- END IF;
- END IF;
- END IF;
- END;
- $$ LANGUAGE 'plpgsql';
- CREATE TRIGGER T BEFORE INSERT OR UPDATE ON buys
- FOR EACH ROW EXECUTE PROCEDURE trigf();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement