-- Creating Triggers


CREATE OR REPLACE FUNCTION br001_crtl_plate_chk() RETURNS trigger AS $br001_crtl_plate_chk$
DECLARE
   cnt           INTEGER;
   v_cell_plate  CODE;
BEGIN

   select code into v_cell_plate from sample_types where id  = NEW.saty_id;

   -- Check if the sample is of type "Cell Plate"
   if v_cell_plate = 'CELL PLATE' then

      -- Check that a Control Plate exists before registering the Cell Plate
      select count(*) into cnt from samples s, sample_types st where s.saty_id = st.id and st.code = 'CONTROL LAYOUT';	 
      IF cnt = 0 THEN
		 -- Doens't make sense, so comment it out
         -- RAISE EXCEPTION 'A Control Plate must exist before you can register Cell Plate: %', NEW.code;
      END IF;

   end if;

   RETURN NEW;

END;
$br001_crtl_plate_chk$ LANGUAGE plpgsql;


CREATE TRIGGER br001_crtl_plate_chk BEFORE INSERT ON samples
    FOR EACH ROW EXECUTE PROCEDURE br001_crtl_plate_chk();
