-- -----------------------------------------------
-- USING SQL TO DEVELOP TIME ORIENTED APPLICATIONS
-- By : Richard T. Snodgrass
-- -----------------------------------------------
--
-- Sequential Referential Integrity (Version 2)
-- INCUMBENTS and POSITIONS are temporal
-- By   : Bruce C. Huang
-- Date : Dec. 12, 1997
--
-- There can only be 1 INSERT/UPDATE trigger for
-- table INCUMBENTS.
-- -----------------------------------------------
REM
REM Code Fragment 5.16 in Oracle 7.3
REM There is no ASSERTIONS in Oracle 7.3, only Triggers.
REM
CREATE OR REPLACE TRIGGER seq_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  NOT EXISTS( SELECT *
                                         FROM  POSITIONS P
                                         WHERE I.PCN = P.PCN
                                           AND P.START_DATE <= I.START_DATE
                                           AND I.START_DATE < P.END_DATE)
                          OR NOT EXISTS( SELECT *
                                         FROM  POSITIONS P
                                         WHERE I.PCN = P.PCN
                                           AND P.START_DATE < I.END_DATE
                                           AND I.END_DATE <= P.END_DATE));

  -- If this SELECT succeeds w/o raising the NO_DATA_FOUND exception,
  --   then this insert/update ensures that this incumbent's PCN
  --   is valid for the period in the POSITIONS table.  The validity
  --   of the POSITIONS table was enfored in the trigger from code 
  --   fragment 5.15


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

END;
/
