CREATE TABLE _mozgasnem_engedely
(
  munkatars_kod integer NOT NULL,
  mozgasnem_kod integer NOT NULL,
  engedelyezett smallint DEFAULT 0,
  CONSTRAINT _mozgasnem_engedely_pkey PRIMARY KEY (munkatars_kod, mozgasnem_kod),
  CONSTRAINT _mozgasnem_engedely_fk1 FOREIGN KEY (munkatars_kod)
      REFERENCES munkatars (kod) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE CASCADE,
  CONSTRAINT _mozgasnem_engedely_fk2 FOREIGN KEY (mozgasnem_kod)
      REFERENCES mozgasnem (kod) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE CASCADE
)
WITHOUT OIDS;

CREATE OR REPLACE FUNCTION tr_mozgasnem_engedely_frissitese()
  RETURNS trigger AS
'begin
   INSERT INTO _mozgasnem_engedely
      (munkatars_kod, mozgasnem_kod)
   Select munkatars.kod, mozgasnem.kod
     FROM munkatars CROSS JOIN mozgasnem
     left outer
     join _mozgasnem_engedely
     on (munkatars.kod = _mozgasnem_engedely.munkatars_kod) and
        (mozgasnem.kod = _mozgasnem_engedely.mozgasnem_kod)
     where _mozgasnem_engedely.munkatars_kod is null
        AND mozgasnem.kod <> 0
        AND mozgasnem.sztorno = 0;
   return new;
end;'
  LANGUAGE plpgsql VOLATILE
  COST 100;
  
CREATE TRIGGER trigger_munkatars_ujtetel
  AFTER INSERT
  ON munkatars
  FOR EACH ROW
  EXECUTE PROCEDURE tr_mozgasnem_engedely_frissitese();
  
CREATE TRIGGER trigger_mozgasnem_ujtetel
  AFTER INSERT
  ON mozgasnem
  FOR EACH ROW
  EXECUTE PROCEDURE tr_mozgasnem_engedely_frissitese();