-- -----------------------------------------------
-- USING SQL TO DEVELOP TIME ORIENTED APPLICATIONS
-- By : Richard T. Snodgrass
-- -----------------------------------------------
--
-- Referential Integrity for temporal tables
-- By   : Bruce C. Huang
-- Date : Dec. 12, 1997
--
-- -----------------------------------------------
REM
REM Code Fragment 5.12 in Oracle 7.3
REM There is no ASSERTIONS in Oracle 7.3, only Triggers.
REM There can exist at most 1 INSERT/UPDATE trigger on a table.
CREATE OR REPLACE TRIGGER cur_ref_integrity
AFTER INSERT or UPDATE on INCUMBENTS
DECLARE 
   valid             INTEGER;
BEGIN
   SELECT 1
   INTO   valid
   FROM   DUAL
   WHERE  NOT EXISTS( SELECT *
                      FROM   INCUMBENTS I
                      WHERE  I.END_DATE = TO_DATE('3000-01-01','YYYY-MM-DD')
                         AND NOT EXISTS( SELECT *
                                         FROM  POSITIONS P
                                         WHERE I.PCN = P.PCN
                                           AND P.END_DATE = TO_DATE('3000-01-01','YYYY-MM-DD')));

  -- If this SELECT succeeds w/o raising the NO_DATA_FOUND exception,
  --   then this insert/update ensures that this incumbent's PCN
  --   is a valid position.

  EXCEPTION
     WHEN NO_DATA_FOUND THEN
        RAISE_APPLICATION_ERROR ( -20001 , 
                                  'Positions Referential Violated' );
        -- Abort the offending transaction, and
        --    rollback to a consistent state.

END;
/
