CREATE OR REPLACE FUNCTION VPX_VDEVICE_FILE_BACKING_TRG_FUNC()
RETURNS TRIGGER
LANGUAGE plpgsql
VOLATILE
AS
$$
DECLARE
 l_upd_key_par INT;
 l_upd_key_chd INT;
 l_backing_id_chd INT;

BEGIN

l_upd_key_chd := NEW.update_key;

SELECT  update_key
INTO    l_upd_key_par
FROM    VPX_VDEVICE_BACKING_REL
WHERE   backing_id = NEW.backing_id;

IF NOT FOUND THEN
  RAISE EXCEPTION USING MESSAGE = 'No parent row', DETAIL = 'VPX_VDEVICE_BACKING_REL Parent Row does not exist!', ERRCODE = 'P0001';
END IF;

IF (l_upd_key_chd <> l_upd_key_par) THEN
  RAISE EXCEPTION USING MESSAGE = 'Not existing value', DETAIL = 'VPX_VDEVICE_FILE_BACKING.UPDATE_KEY value ' || NEW.update_key || ' does not exist in VPX_VDEVICE_BACKING_REL.UPDATE_KEY', ERRCODE = 'P0001';
END IF;

RETURN NEW;

END
$$;

CREATE TRIGGER VPX_VDEVICE_FILE_BACKING_TRG
BEFORE UPDATE OR INSERT
ON VPX_VDEVICE_FILE_BACKING
FOR EACH ROW
EXECUTE PROCEDURE VPX_VDEVICE_FILE_BACKING_TRG_FUNC();