  CREATE OR REPLACE PACKAGE "RELEASE_MANAGER"."PK_LICENCING" IS
/*
------------------------------
||  Last Modified:  G.Huddy
||  Modified Date:  19/Aug/2008
||  Spec Version:   1.0
------------------------------
*/

   TYPE typeCur IS REF CURSOR;

    /*================================================================================================*/
   PROCEDURE ADD_LICENCE ( PvId IN NUMBER, licenceId IN NUMBER, UserId IN NUMBER );
   PROCEDURE REMOVE_LICENCE ( PvId IN NUMBER, licenceId IN NUMBER, UserId IN NUMBER );
   PROCEDURE CLONE_LICENCING( fromPvId IN NUMBER, toPvId IN NUMBER, UserId IN NUMBER );
   FUNCTION  IS_LICENCED( PvId IN NUMBER, licenceId IN NUMBER) RETURN NUMBER;
   PROCEDURE REMOVE_ALL_LICENCING( PvId IN NUMBER, UserId IN NUMBER );
   /*================================================================================================*/

END PK_LICENCING;

/
--------------------------------------------------------
--  DDL for Package PK_PACKAGE
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE "RELEASE_MANAGER"."PK_PACKAGE" 
IS
/*
------------------------------
||  Last Modified:  Jeremy Tweddle
||  Modified Date:  24/08/2007
||
------------------------------
*/
   TYPE typecur IS REF CURSOR;

   /*
    * Carriage-return line-feed character sequence.
    */
   CRLF CONSTANT VARCHAR2(2 CHAR) := unistr('\000D\000A');

/*================================================================================================*/
   PROCEDURE new_version (
      nlastpvid                   IN       NUMBER,
      snewpkgversion              IN       VARCHAR2 DEFAULT NULL,
      cbuildtype                  IN       CHAR,
      cchangetype                 IN       CHAR,
      nsettopvid                  IN       NUMBER DEFAULT NULL,
      nrtagid                     IN       NUMBER,
      nuserid                     IN       NUMBER,
      enumissues_state_imported   IN       NUMBER,
      returnpvid                  OUT      NUMBER
   );

   PROCEDURE change_state (
      pvid       IN   NUMBER,
      newstate   IN   package_versions.dlocked%TYPE,
      userid     IN   NUMBER
   );

   PROCEDURE new_patch (
      snewpatchversion   IN       package_versions.pkg_version%TYPE,
      nparentpvid        IN       NUMBER,
      spatchidlist       IN       VARCHAR2,
      nuserid            IN       NUMBER,
      returnpatchid      OUT      NUMBER
   );

   PROCEDURE obsolete_patch (
      patchid            IN   NUMBER,
      isobsolete         IN   CHAR,
      obsoletecomments   IN   VARCHAR2,
      userid             IN   NUMBER
   );

   PROCEDURE obsolete_patches (
      spatchidlist       IN   VARCHAR2,
      isobsolete         IN   CHAR,
      obsoletecomments   IN   VARCHAR2,
      userid             IN   NUMBER
   );

   PROCEDURE destroy_package (
      pvid               IN       NUMBER,
      overridewarnings   IN       CHAR DEFAULT 'N',
      problemstring      OUT      VARCHAR2
   );
   
   PROCEDURE destroy_package_extended (
      pvid               IN       NUMBER,
      rtagid             IN       NUMBER,
      overridewarnings   IN       NUMBER DEFAULT 0,
      RESULTS            OUT      SYS_REFCURSOR
);
   PROCEDURE add_process (
      nprocid         IN   processes.proc_id%TYPE,
      shealthtag      IN   processes.proc_name%TYPE,
      sprocdesc       IN   processes.proc_description%TYPE,
      scmdinterface   IN   processes.run_as%TYPE,
      spkgowner       IN   processes.pkg_owner%TYPE,
      sisinterface    IN   processes.is_interface%TYPE,
      npvid           IN   package_processes.pv_id%TYPE,
      nuserid         IN   NUMBER
   );

   PROCEDURE add_package_process (
      nprocidlist   IN   VARCHAR2,
      npvid         IN   package_processes.pv_id%TYPE,
      nuserid       IN   NUMBER
   );



   PROCEDURE remove_process (
      nprocid   IN   package_processes.proc_id%TYPE,
      npvid     IN   package_processes.pv_id%TYPE,
      nuserid   IN   NUMBER
   );

   PROCEDURE move_package (
   	  npvid  			  IN package_versions.pv_id%TYPE,
	  nrtagid 			  IN release_tags.rtag_id%TYPE,
	  nnewrtagid 		  IN release_tags.rtag_id%TYPE,
	  nuserid			  IN NUMBER
   );

   PROCEDURE modify_product_state (
   	  npvid IN package_versions.pv_id%TYPE,
	  nrtagid IN release_tags.rtag_id%TYPE,
	  nstateid IN product_states.state_id%TYPE,
	  nuserid IN NUMBER
   );

   PROCEDURE add_code_review_url (
        npvid           IN    NUMBER,
        nprojid         IN    NUMBER,
        surl            IN    VARCHAR2,
        sreason         IN    VARCHAR2,
        ddateofreview   IN    VARCHAR2
   );

   PROCEDURE update_code_review_url (
        ncrid           IN    NUMBER,
        nprojid         IN    NUMBER,
        surl            IN    VARCHAR2,
        sreason         IN    VARCHAR2,
        ddateofreview   IN    VARCHAR2
   );

   PROCEDURE remove_code_review_url (
        ncrid           IN    NUMBER
   );
   
   PROCEDURE SET_RIPPLE_STOP (
        nPVID IN RELEASE_CONTENT.PV_ID%TYPE,
        nRtagId IN RELEASE_CONTENT.RTAG_ID%TYPE,
        nUserId IN NUMBER,
        cMode IN CHAR
   );
   
/*================================================================================================*/
END pk_package;

/

  GRANT EXECUTE ON "RELEASE_MANAGER"."PK_PACKAGE" TO "DEPLOYMENT_MANAGER";
  GRANT DEBUG ON "RELEASE_MANAGER"."PK_PACKAGE" TO "DEPLOYMENT_MANAGER";
--------------------------------------------------------
--  DDL for Package PK_PLANNED
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE "RELEASE_MANAGER"."PK_PLANNED" IS
/*
------------------------------
||  Last Modified:  G.Huddy
||  Modified Date:  28/May/2008
||  Spec Version:   1.1
------------------------------
*/

	TYPE typeCur IS REF CURSOR;

    /*================================================================================================*/
	PROCEDURE ADD_PACKAGE ( newPvId IN NUMBER, ViewId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER, OPR IN CHAR DEFAULT 'R'  );
	PROCEDURE REMOVE_PACKAGE ( PvId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER );
	FUNCTION GET_PACKAGE_VIEW ( PvId IN NUMBER, RtagId IN NUMBER ) RETURN NUMBER;
	PROCEDURE GET_VIEW_CONTENT ( RtagId IN NUMBER, ViewId IN NUMBER, RecordSet OUT typeCur );
	PROCEDURE CHANGE_PACKAGE_VIEW ( PvId IN NUMBER, RtagId IN NUMBER, NewViewId IN NUMBER );
	PROCEDURE MERGE_PACKAGE ( newPvId IN NUMBER, ViewId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER, mergeOperation IN CHAR);
	/*================================================================================================*/

END PK_PLANNED;

/
--------------------------------------------------------
--  DDL for Package PK_PROJECT
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE "RELEASE_MANAGER"."PK_PROJECT" IS

    TYPE typecur IS REF CURSOR;

    /*------------------------------------------------------------------------*/
    PROCEDURE update_base_url (
        nprojid   IN  projects.proj_id%TYPE,
        sbaseurl  IN  VARCHAR2
    );
    /*------------------------------------------------------------------------*/
    PROCEDURE update_project_config (
    nprojid   IN  projects.proj_id%TYPE,
    sbaseurl  IN  VARCHAR2,
    sjirakey  IN  VARCHAR2
    );
    /*------------------------------------------------------------------------*/

    END pk_project;

/
--------------------------------------------------------
--  DDL for Package PK_RELEASE
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE "RELEASE_MANAGER"."PK_RELEASE" IS
/*
------------------------------
||  Last Modified:  S.Vukovic
||  Modified Date:  12/Sep/2005
||  Body Version:   3.0
------------------------------
*/

	TYPE typeCur IS REF CURSOR;

    /*================================================================================================*/
	PROCEDURE New_Release ( sReleaseName IN VARCHAR2, sReleaseComments IN VARCHAR2, nProjId IN NUMBER, nSourceRtagId IN NUMBER, sIsBranched IN CHAR, nUserId IN NUMBER,cOfficial IN CHAR DEFAULT 'N' );
	PROCEDURE Update_Release ( nRtagId IN NUMBER, sReleaseName IN VARCHAR2, sReleaseComments IN VARCHAR2, nParentRtagId IN NUMBER, nMASSRtagId IN NUMBER, nConfigSpecBranch IN VARCHAR2, sOwnerEmail IN VARCHAR2, nUserId IN NUMBER, cState IN VARCHAR, nBuildAge in NUMBER,cLxr in CHAR );
	PROCEDURE MOVE_RELEASE ( sRtagIdList IN VARCHAR2, nProjId IN NUMBER, nUserId IN NUMBER  );
	PROCEDURE Destroy_Release ( nRtagId IN NUMBER, nUserId IN NUMBER );
	PROCEDURE Import_Release_Contents ( nSourceRtagId IN NUMBER, nTargetRtagId IN NUMBER, nUserId IN NUMBER,nMode IN NUMBER default 0 );
	PROCEDURE Clean_Release_Contents ( nRtagId IN NUMBER, nUserId IN NUMBER );
	FUNCTION GET_PARENT_RTAG ( nRtagId IN NUMBER, nSourceRtagId IN NUMBER, cIsBranch IN CHAR ) RETURN NUMBER;
	PROCEDURE UPDATE_DISPLAY_ORDER ( nProjId IN NUMBER );
	PROCEDURE GET_VIEW_CONTENT ( RtagId IN NUMBER, ViewId IN NUMBER, RecordSet OUT typeCur );
	PROCEDURE ADD_PACKAGE ( newPvId IN NUMBER, ViewId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER );
	--PROCEDURE ADD_DEPRECATE_PACKAGE ( newPvId IN NUMBER, ViewId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER, nPkgId IN NUMBER );
	PROCEDURE REPLACE_PACKAGE ( newPvId IN NUMBER, oldPvId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER );
	PROCEDURE REMOVE_PACKAGE ( PvId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER );
	PROCEDURE REMOVE_MATCHING_PACKAGE ( PvId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER );
	FUNCTION GET_PACKAGE_VIEW ( PvId IN NUMBER, RtagId IN NUMBER ) RETURN NUMBER;
	PROCEDURE RUN_POST_ACTIONS ( PvId IN NUMBER, RtagId IN NUMBER );
	PROCEDURE RUN_POST_ACTIONS_BULK ( PvId IN NUMBER );
	PROCEDURE CHANGE_PACKAGE_VIEW ( PvId IN NUMBER, RtagId IN NUMBER, NewViewId IN NUMBER );
	PROCEDURE ADD_RELEASE_REFERENCE ( nRtagId IN NUMBER, nRefRtagId IN NUMBER, ProblemString OUT VARCHAR2 );
	PROCEDURE REMOVE_RELEASE_REFERENCE ( nRtagId IN NUMBER, nRefRtagId IN NUMBER );
	PROCEDURE CAN_USER_WRITE_TO_RELEASE ( RtagId IN NUMBER, PvId IN NUMBER, Permission IN CHAR );
  PROCEDURE SET_RELEASE_MODIFIED (nRtagId IN NUMBER );
  PROCEDURE ADD_RELEASE_SDK ( nRtagId IN NUMBER, nSdktagId IN NUMBER, nUserId IN NUMBER, bDelete IN  NUMBER, nInsertCount OUT NUMBER, curReturn OUT typeCur );
  PROCEDURE REMOVE_RELEASE_SDK ( nRtagId IN NUMBER, nSdktagId IN NUMBER );
  FUNCTION CAN_ADD_PKG_TO_RELEASE ( nRtagId IN NUMBER, nPvid in NUMBER ) RETURN NUMBER;

	/*================================================================================================*/

END PK_RELEASE;

/
--------------------------------------------------------
--  DDL for Package PK_RMAPI
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE "RELEASE_MANAGER"."PK_RMAPI" 
IS
   TYPE typecur IS REF CURSOR;

   FUNCTION package_dependencies (pkgname VARCHAR2, pkgversion VARCHAR2)
      RETURN typecur;

   FUNCTION wip_iteration_package (
      projname        VARCHAR2,
      iterationname   VARCHAR2,
      pkgname         VARCHAR2
   )
      RETURN typecur;

   FUNCTION auto_make_vcsrelease (
      rtagid                   IN   NUMBER,
      pkgname                  IN   VARCHAR2,
      vext                     IN   VARCHAR2,
      newpkgversion            IN   VARCHAR2,
      vcstag                   IN   VARCHAR2,
      dependenciesimportlist   IN   VARCHAR2,
      isrippled                IN   NUMBER,
      username                 IN   VARCHAR2
   )
      RETURN NUMBER;

FUNCTION auto_make_vcsrelease2 (
      rtagid                   IN   NUMBER,
      pkgname                  IN   VARCHAR2,
      vext                     IN   VARCHAR2,
      newpkgversion            IN   VARCHAR2,
      vcstag                   IN   VARCHAR2,
      dependenciesimportlist   IN   relmgr_varchar2_tab_t,
      isrippled                IN   NUMBER,
      username                 IN   VARCHAR2
   )      
      RETURN NUMBER;

   PROCEDURE import_dependencies (
      pvid                     IN   NUMBER,
      dependenciesimportlist   IN   VARCHAR2,
      userid                   IN   NUMBER
   );

    PROCEDURE import_dependencies2 (
    pvid                     IN   NUMBER,
    dependenciesimportlist   IN   relmgr_varchar2_tab_t,
    userid                   IN   NUMBER
    );

   FUNCTION return_last_package_version (pkgname IN VARCHAR2, rtagid IN NUMBER)
      RETURN VARCHAR2;

   FUNCTION return_wip (pkgname IN VARCHAR2, rtagid IN NUMBER)
      RETURN VARCHAR2;

   PROCEDURE update_dash_board (rtagid IN NUMBER);

   FUNCTION exclude_from_build (
      pvid          IN   NUMBER,
      spkgversion   IN   VARCHAR2,
      rtagid        IN   NUMBER,
      username      IN   VARCHAR2
   )
      RETURN NUMBER;

   FUNCTION exclude_indirect_from_build (
      pvid          IN   NUMBER,
      spkgversion   IN   VARCHAR2,
      rtagid        IN   NUMBER,
      username      IN   VARCHAR2,
      rootpvid      IN   NUMBER,
      rootcause     IN   VARCHAR2,
      rootfile      IN   VARCHAR2
   )
      RETURN NUMBER;

   PROCEDURE insert_abt_actionlog (rconid IN NUMBER, action IN VARCHAR2);

   FUNCTION insert_package_metrics (
      rtagid IN NUMBER,
      pkgname IN VARCHAR2,
      vext IN VARCHAR2,
      metricstring IN VARCHAR2
   )
      RETURN NUMBER;

   PROCEDURE update_release_metrics (rtagid IN NUMBER);

   FUNCTION return_vcs_tag(pvid IN NUMBER) RETURN VARCHAR2;

   PROCEDURE update_vcs_details(ipv_id IN NUMBER, vcstag IN VARCHAR2, user_id IN NUMBER);

   FUNCTION isSVN( pkgid IN NUMBER ) RETURN NUMBER;

   FUNCTION isSVNbyName( pkgname IN VARCHAR2 ) RETURN NUMBER;

   FUNCTION new_build_instance( rtag_id IN NUMBER, pv_id IN NUMBER, reason IN CHAR, buildRef IN VARCHAR2 default null) return NUMBER;

   FUNCTION update_build_instance( nbuild_id IN NUMBER, npv_id IN NUMBER default null, nstate IN CHAR default null ) return NUMBER;

   FUNCTION update_build_ref( nrtag_id IN NUMBER, buildRef IN VARCHAR2, buildRefNew IN VARCHAR2 default null ) return NUMBER;

   FUNCTION insert_test_run( build_id IN NUMBER, name IN VARCHAR2, outcome IN VARCHAR2, platform IN VARCHAR2, stype IN VARCHAR2, duration IN NUMBER default null, message IN CLOB default null) return NUMBER;


END pk_rmapi;

/

  GRANT EXECUTE ON "RELEASE_MANAGER"."PK_RMAPI" TO "RM_READONLY";
  GRANT EXECUTE ON "RELEASE_MANAGER"."PK_RMAPI" TO "MS_READONLY";
  GRANT EXECUTE ON "RELEASE_MANAGER"."PK_RMAPI" TO "DM_READONLY";
--------------------------------------------------------
--  DDL for Package PK_WORK_IN_PROGRESS
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE "RELEASE_MANAGER"."PK_WORK_IN_PROGRESS" IS
/*
------------------------------
||  Last Modified:  S.Vukovic
||  Modified Date:  2/May/2005
||  Spec Version:   1.0
------------------------------
*/

	TYPE typeCur IS REF CURSOR;

    /*================================================================================================*/
	PROCEDURE ADD_PACKAGE ( newPvId IN NUMBER, ViewId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER );
	PROCEDURE REMOVE_PACKAGE ( PvId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER );
	PROCEDURE REMOVE_PACKAGE_BULK ( PvIdList IN VARCHAR2, RtagId IN NUMBER, UserId IN NUMBER );

	FUNCTION GET_PACKAGE_VIEW ( PvId IN NUMBER, RtagId IN NUMBER ) RETURN NUMBER;
	PROCEDURE GET_VIEW_CONTENT ( RtagId IN NUMBER, ViewId IN NUMBER, RecordSet OUT typeCur );
	PROCEDURE CHANGE_PACKAGE_VIEW ( PvId IN NUMBER, RtagId IN NUMBER, NewViewId IN NUMBER );
	/*================================================================================================*/

END PK_WORK_IN_PROGRESS;

/
--------------------------------------------------------
--  DDL for Package RM_ISSUES
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE "RELEASE_MANAGER"."RM_ISSUES" AS

	TYPE T_Cur IS REF CURSOR;

	FUNCTION VerIsGrtrThanOrEqlToStart( XXstart IN NUMBER, XX IN NUMBER, YYstart IN NUMBER, YY IN NUMBER, ZZstart IN NUMBER, ZZ IN NUMBER ) RETURN NUMBER;
	FUNCTION VersionIsBetween( version IN VARCHAR2, version_start IN VARCHAR2, version_end IN VARCHAR ) RETURN NUMBER;
	FUNCTION VerIsLessThanOrEqlToEnd( XXend IN NUMBER, XX IN NUMBER, YYend IN NUMBER, YY IN NUMBER, ZZend IN NUMBER, ZZ IN NUMBER ) RETURN NUMBER;
	FUNCTION GetPkgId( pkgName IN VARCHAR2 ) RETURN NUMBER;

	PROCEDURE AllIssues( vCursor OUT T_Cur, pkg_name IN VARCHAR2, version_start IN VARCHAR2, version_end IN VARCHAR2 );
	PROCEDURE LoadIssuesTable( vCursor OUT T_Cur, pkg_name IN VARCHAR2, version_start IN VARCHAR2, version_end IN VARCHAR2 );
	PROCEDURE InsertIssuesForDepends( pvID IN NUMBER, top_pkgID IN NUMBER, top_pkgName IN VARCHAR2, top_pvID IN NUMBER, top_pkgVer IN VARCHAR2 );

END Rm_Issues;

/
--------------------------------------------------------
--  DDL for Package Body PK_APP_UTILS
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE BODY "RELEASE_MANAGER"."PK_APP_UTILS" IS

/*
------------------------------
||  Last Modified:  S.Vukovic
||  Modified Date:  26/Apr/2005
||  Body Version:   1.0
------------------------------
*/


/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE GET_CURRENT_PARAMETERS ( ProjId IN VARCHAR2, RtagId IN VARCHAR2, records OUT typeCur)   IS


BEGIN


	IF (NOT RtagId IS NULL) THEN
		-- Case with RTAG_ID present
		OPEN records FOR
		SELECT rt.PROJ_ID,
			   rt.RTAG_ID AS RTAG_ID
		  FROM RELEASE_TAGS rt
		 WHERE rt.RTAG_ID = TO_NUMBER(RtagId);

	ELSIF (NOT ProjId IS NULL) THEN
		-- Case with PROJ_ID present
		OPEN records FOR
		SELECT TO_NUMBER(ProjId) AS PROJ_ID,
			   -1 AS RTAG_ID
		  FROM DUAL;

	ELSE
		-- Case with none present
		OPEN records FOR
		SELECT -1 AS PROJ_ID,
			   -1 AS RTAG_ID
		  FROM DUAL;

	END IF;




   	--RETURN records;

END;
/*-------------------------------------------------------------------------------------------------------*/
END PK_APP_UTILS;

/

  GRANT EXECUTE ON "RELEASE_MANAGER"."PK_APP_UTILS" TO "DEPLOYMENT_MANAGER";
--------------------------------------------------------
--  DDL for Package Body PK_BLATAPI
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE BODY "RELEASE_MANAGER"."PK_BLATAPI" 
IS
/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE add_pkg_replica (
      sdisplay_name          IN   VARCHAR2,
      sserver_name           IN   VARCHAR2,
      sdescription           IN   VARCHAR2,
      sactive                IN   CHAR,
      smode                  IN   CHAR
   )
   IS
      nrecordnumber   NUMBER;
      nserver_id       NUMBER;
   BEGIN

      INSERT INTO blat_servers(blat_display_name, blat_server_name,blat_description,blat_enable,blat_mode)
            VALUES (sdisplay_name,sserver_name,sdescription, NVL(sactive,'N'), NVL(smode,'N'));

   EXCEPTION
      WHEN DUP_VAL_ON_INDEX
      THEN
         raise_application_error (-20000,
                                 'Cannot have duplicate machines.'
                                 );
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE delete_pkg_replica (sserver_id_list IN VARCHAR2)
   IS
   BEGIN
      DELETE FROM blat_servers
            WHERE blat_id IN (
                     SELECT * FROM THE
                              (SELECT CAST
                                          (in_list_number (sserver_id_list) AS relmgr_number_tab_t
                                          )
                                 FROM DUAL
                              ));
   END;


/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE update_pkg_replica (
      nserver_id             IN   NUMBER,
      sdisplay_name          IN   VARCHAR2,
      sserver_name           IN   VARCHAR2,
      sdescription           IN   VARCHAR2,
      sactive                IN   CHAR,
      smode                  IN   CHAR
   )
   IS
   BEGIN
      UPDATE blat_servers
         SET blat_display_name = sdisplay_name,
             blat_server_name = sserver_name,
             blat_description = sdescription,
             blat_enable = NVL(sactive, 'N'),
             blat_mode = NVL(smode, 'N')
      WHERE blat_id = nserver_id;

   PK_BLATAPI.set_pkg_replica_changed(nserver_id);

   EXCEPTION
      WHEN DUP_VAL_ON_INDEX
      THEN
         raise_application_error (-20000,
                                 'Cannot have duplicate machines.'
                                 );


   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE set_pkg_replica_changed( nserver_id IN   NUMBER)
   IS
   BEGIN
    UPDATE blat_servers
    SET blat_seqnum = SEQ_BLAT_MOD.NEXTVAL,
        blat_timestamp = current_timestamp
    WHERE blat_id = nserver_id;    
   END;

END PK_BLATAPI;

/
--------------------------------------------------------
--  DDL for Package Body PK_BUILDAPI
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE BODY "RELEASE_MANAGER"."PK_BUILDAPI" 
IS
   /*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE add_product_component (
      npvid           IN   NUMBER,
      sosname         IN   VARCHAR2,
      sorigfilepath   IN   VARCHAR2,
      sfilename       IN   VARCHAR2,
      sdestfilepath   IN   VARCHAR2,
      nbytesize       IN   NUMBER,
      scrccksum       IN   VARCHAR2
   )
   IS
      nosid   NUMBER;
   BEGIN
      /*--------------- Business Rules Here -------------------*/
      -- OS Name Requirements --
      IF (sosname IS NULL)
      THEN
         raise_application_error (-20000, 'OsName cannot be NULL.');
      END IF;

      -- File Requirements --
      IF (NOT sfilename IS NULL)
      THEN
         IF (nbytesize IS NULL)
         THEN
            raise_application_error (-20000, 'Byte Size cannot be NULL.');
         ELSIF (scrccksum IS NULL)
         THEN
            raise_application_error (-20000, 'CRC CKSUM cannot be NULL.');
         END IF;
      END IF;

      -- Folder Requirements --
      -- No requirements for now.

      /*-------------------------------------------------------*/

      -- Get OsId
      nosid := get_osid (sosname);

      -- Insert component entry
      INSERT INTO product_components
                  (pv_id, os_id, file_path, file_name, destination_path,
                  byte_size, crc_cksum
                  )
         VALUES (npvid, nosid, sorigfilepath, sfilename, sdestfilepath,
                  nbytesize, scrccksum
                  );
   EXCEPTION
      WHEN DUP_VAL_ON_INDEX
      THEN
         raise_application_error (-20000,
                                 'Cannot have duplicate product components.'
                                 );
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE remove_all_product_components (
      npvid     IN   NUMBER,
      sosname   IN   VARCHAR2
   )
   IS
      nosid   NUMBER;
   BEGIN
/*--------------- Business Rules Here -------------------*/
/*-------------------------------------------------------*/

      -- Get OsId
      nosid := get_osid (sosname);

      -- Delete component entry
      DELETE FROM product_components pc
            WHERE pc.pv_id = npvid AND pc.os_id = nosid;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   FUNCTION get_osid (sosname IN VARCHAR2)
      RETURN NUMBER
   IS
      code   NUMBER;
   BEGIN
      -- Get Platform Code --
      SELECT pf.code
      INTO code
      FROM platforms pf
      WHERE UPPER (pf.NAME) = UPPER (sosname);

      RETURN code;
   EXCEPTION
      WHEN NO_DATA_FOUND
      THEN
         raise_application_error
            (-20000,
               'Platform '
            || sosname
            || ' is not valid. It needs to be added to PLATFORMS table in Release Manager.'
            );
         RAISE;
   END;

/*-------------------------------------------------------------------------------------------------------*/
 PROCEDURE update_build_service_info (
      sdatabaseserver   IN   VARCHAR2,
      sarchiveserver    IN   VARCHAR2,
      smailserver       IN   VARCHAR2,
      smailsender       IN   VARCHAR2,
      faultmlist        IN   VARCHAR2,
      sdiskspace        IN   VARCHAR2,
      ssbommanagement   IN   VARCHAR2,
      lxrserver         IN   VARCHAR2
   )
   IS
   BEGIN
      UPDATE build_service_config
         SET config = sdatabaseserver
      WHERE service = 'DATABASE SERVER';

      UPDATE build_service_config
         SET config = sarchiveserver
      WHERE service = 'ARCHIVE SERVER';

      UPDATE build_service_config
         SET config = smailserver
      WHERE service = 'MAIL SERVER';

      UPDATE build_service_config
         SET config = smailsender
      WHERE service = 'BUILD FAILURE MAIL SENDER';

      UPDATE build_service_config
         SET config = faultmlist
      WHERE service = 'FAULT EMAIL ADDRESS LIST';

      UPDATE build_service_config
         SET config = sdiskspace
      WHERE service = 'DPKG_ARCHIVE DISK SPACE USED';

      UPDATE build_service_config
         SET config = ssbommanagement
      WHERE service = 'SBOM MANAGEMENT';

      UPDATE build_service_config
         SET config = lxrserver
      WHERE service = 'LXR SERVER';
   END;



/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE add_gbe_machtype (sgbevalue IN VARCHAR2, sgbeclass IN NUMBER)
   IS
      gbe_id   NUMBER;
   BEGIN
      -- Get GBE_ID
      SELECT seq_gbe_id.NEXTVAL
      INTO gbe_id
      FROM DUAL;

      INSERT INTO gbe_machtype
                  (gbe_id, gbe_value, bm_id )
         VALUES (gbe_id, sgbevalue, sgbeclass );
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE remove_gbe_machtype (ngbe_id IN NUMBER)
   IS
   BEGIN
      DELETE FROM gbe_machtype
            WHERE gbe_id = ngbe_id;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE update_gbe_machtype (ngbe_id IN NUMBER, sgbevalue IN VARCHAR2, sgbeclass IN NUMBER)
   IS
   BEGIN
      UPDATE gbe_machtype
         SET gbe_value = sgbevalue,
             bm_id = sgbeclass
      WHERE gbe_id = ngbe_id;
   END;

/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE add_buildmachine (sbmvalue IN VARCHAR2)
   IS
      bm_id   NUMBER;
   BEGIN
      -- Get BM_ID
      SELECT seq_bm_id.NEXTVAL
      INTO bm_id
      FROM DUAL;

      INSERT INTO build_machines
                  (bm_id, bm_name)
         VALUES (bm_id, sbmvalue );
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE remove_buildmachine (nbm_id IN NUMBER)
   IS
   BEGIN
      DELETE FROM build_machines
            WHERE bm_id = nbm_id;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE update_buildmachine (nbm_id IN NUMBER, sbmvalue IN VARCHAR2)
   IS
   BEGIN
      UPDATE build_machines
         SET bm_name = sbmvalue
         WHERE bm_id = nbm_id;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE delete_daemon (srconidlist IN VARCHAR2)
   IS
   BEGIN
      -- Entries in the daemon_action_log, run_level and abt_action_log tables must be deleted first.
      DELETE FROM daemon_action_log
            WHERE rcon_id IN (
                     SELECT *
                     FROM THE
                              (SELECT CAST
                                          (in_list_number (srconidlist) AS relmgr_number_tab_t
                                          )
                                 FROM DUAL
                              ));

      DELETE FROM run_level
            WHERE rcon_id IN (
                     SELECT *
                     FROM THE
                              (SELECT CAST
                                          (in_list_number (srconidlist) AS relmgr_number_tab_t
                                          )
                                 FROM DUAL
                              ));

      DELETE FROM abt_action_log
            WHERE rcon_id IN (
                     SELECT *
                     FROM THE
                              (SELECT CAST
                                          (in_list_number (srconidlist) AS relmgr_number_tab_t
                                          )
                                 FROM DUAL
                              ));

      -- Once entries in daemon_action_log, run_level and abt_action_log are removed, the daemon is deleted.
      DELETE FROM release_config
            WHERE rcon_id IN (
                     SELECT *
                     FROM THE
                              (SELECT CAST
                                          (in_list_number (srconidlist) AS relmgr_number_tab_t
                                          )
                                 FROM DUAL
                              ));
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE remove_daemon (srconidlist IN VARCHAR2)
   IS
   oRconIdList RELMGR_NUMBER_TAB_t := RELMGR_NUMBER_TAB_t();

   BEGIN

   oRconIdList := IN_LIST_NUMBER ( srconidlist );

      -- Break the linkage between the release_config and the build_machine_config

      -- Delete the linkage between the two tables.
       UPDATE release_config
         SET daemon_hostname = NULL,
             bmcon_id = NULL
      WHERE rcon_id IN ( SELECT * FROM TABLE ( CAST ( oRconIdList AS RELMGR_NUMBER_TAB_t ) ) );
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE insert_schedule_info (
      dschedulepause     IN   DATE,
      dscheduleresume    IN   DATE,
      crepeat            IN   VARCHAR2,
      cindefinitepause   IN   VARCHAR2
   )
   IS
      nscheduledid   NUMBER;
   BEGIN
      -- Get Next Available Scheduled Id
      SELECT seq_scheduled_id.NEXTVAL
      INTO nscheduledid
      FROM DUAL;

      INSERT INTO run_level_schedule
         VALUES (nscheduledid, dschedulepause, dscheduleresume, crepeat,
                  cindefinitepause);
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE delete_schedule (nscheduleid IN NUMBER)
   IS
   BEGIN
      DELETE FROM run_level_schedule
            WHERE scheduled_id = nscheduleid;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE set_infinite_pause
   IS
      nscheduledid   NUMBER;
   BEGIN
      -- Get Next Available Scheduled Id
      SELECT seq_scheduled_id.NEXTVAL
      INTO nscheduledid
      FROM DUAL;

      INSERT INTO run_level_schedule
         VALUES (nscheduledid, ora_sysdatetime, NULL, NULL, 'P');
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE set_finite_pause (duration IN NUMBER)
   IS
      nscheduledid   NUMBER;
      currentDate    DATE := ora_sysdatetime;
   BEGIN

      -- Get Next Available Scheduled Id
      SELECT seq_scheduled_id.NEXTVAL
      INTO nscheduledid
      FROM DUAL;

      INSERT INTO run_level_schedule
         VALUES (nscheduledid, currentDate, currentDate + duration/(24*60), 0, 'F');
      COMMIT;

      -- Ensure that we have only ONE finite pause by deleting all old ones
      -- Under race conditions the last one wins
      DELETE FROM run_level_schedule
        WHERE SCHEDULED_ID < nscheduledid
        AND INDEFINITE_PAUSE = 'F';
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE set_resume
   IS
   BEGIN
      DELETE FROM run_level_schedule
            WHERE indefinite_pause in ('F', 'P' );
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE delete_out_of_date_schedule
   IS
   BEGIN
      DELETE FROM run_level_schedule
            WHERE scheduled_resume < ora_sysdatetime AND repeat = 0;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE set_daemon_resume (nrconid IN NUMBER)
   IS
   BEGIN
      UPDATE run_level
         SET PAUSE = NULL
      WHERE rcon_id = nrconid;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE set_daemon_pause (nrconid IN NUMBER)
   IS
   BEGIN
      UPDATE run_level
         SET PAUSE = 1
      WHERE rcon_id = nrconid;
   END;
/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE set_daemon_disable (nrconid NUMBER)
   IS
   BEGIN
      UPDATE run_level
         SET PAUSE = 2
      WHERE rcon_id = nrconid;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE set_daemon_states (nrtagid NUMBER, nstate NUMBER)
   IS
   BEGIN
     UPDATE run_level
     SET pause = nstate
     WHERE rcon_id IN
     (SELECT rc.rcon_id FROM release_config rc WHERE rc.rtag_id = nrtagid);
   END;

/*-------------------------------------------------------------------------------------------------------*/
   -- inserts a new daemon instruction
   -- This is for use by the Release Manager Website code.
   --
   PROCEDURE insert_daemon_inst
   ( nOp_code IN NUMBER
   , nRtag_id IN NUMBER
   , nPv_id IN NUMBER
   , nSchedDate IN DATE
   , nRepeatSecs IN NUMBER
   , nAddedDate IN DATE
   , nUser_id IN NUMBER
   ) IS
      nInstId   NUMBER;
   BEGIN
      -- Get Next Available Scheduled Id
      SELECT seq_daemon_instruction_id.NEXTVAL
      INTO nInstId
      FROM DUAL;

      INSERT INTO Daemon_Instructions
         VALUES (nInstId, nOp_code, nRtag_id,
                  nPv_id, nSchedDate, nRepeatSecs,
                  nAddedDate, nUser_id, '0');

   -- Mark the Release as modified for build purposes
   PK_RELEASE.SET_RELEASE_MODIFIED(nRtag_id);

   EXCEPTION
      WHEN DUP_VAL_ON_INDEX
      THEN
         raise_application_error (-20000,
                                 'Table already contains a record with the specified OPERATION, RELEASE, and PACKAGE VERSION'
                                 );
      WHEN OTHERS
      THEN
         raise;

   END insert_daemon_inst;

/*-------------------------------------------------------------------------------------------------------*/
   -- Deletes a daemon instruction matching the specified instruction ID
   --
   PROCEDURE del_daemon_inst
   ( nInstId IN NUMBER
   ) IS

   BEGIN
      DELETE FROM Daemon_Instructions
      WHERE DAEMON_INSTRUCTIONS_ID = nInstId;

   END del_daemon_inst;

/*-------------------------------------------------------------------------------------------------------*/
   -- Deletes a daemon instruction matching the specified op-code, ratag, and pv_id
   --
   PROCEDURE del_daemon_inst_by_rtag_pvid(
      nOp_code IN NUMBER,
      nRtag_id IN NUMBER,
      nPv_id IN NUMBER
   ) IS
   BEGIN
      DELETE FROM Daemon_Instructions
      WHERE OP_CODE = nOp_code
      AND RTAG_ID = nRtag_id
      AND PV_ID   = nPv_id;

   END del_daemon_inst_by_rtag_pvid;

/*-------------------------------------------------------------------------------------------------------*/
   -- Updates a daemon instruction
   -- This is for use by the Release Manager Website code.
   --
   PROCEDURE update_daemon_inst
   ( nInstId IN NUMBER
   , nOp_code IN NUMBER
   , nRtag_id IN NUMBER
   , nPv_id IN NUMBER
   , nSchedDate IN DATE
   , nRepeatSecs IN NUMBER
   , nAddedDate IN DATE
   , nUser_id IN NUMBER
   ) IS
      CURSOR daemon_inst_cur IS
         SELECT *
         FROM daemon_instructions di
         WHERE di.DAEMON_INSTRUCTIONS_ID = nInstId;

      daemon_inst_rec   daemon_inst_cur%ROWTYPE;

      exc_inst_removed EXCEPTION;
   BEGIN
      OPEN daemon_inst_cur;

      FETCH daemon_inst_cur
      INTO daemon_inst_rec;

      IF daemon_inst_cur%FOUND THEN

         UPDATE Daemon_Instructions
         SET op_code = nOp_code,
            rtag_id = nRtag_id,
            pv_id   = nPv_id,
            scheduled_datetime = nSchedDate,
            repeat_secs = nRepeatSecs,
            added_datetime = nAddedDate,
            user_id = nUser_id,
            in_progress = '0'
         WHERE daemon_instructions_id = nInstId;
      ELSE
         raise exc_inst_removed;
      END IF;

      CLOSE daemon_inst_cur;

      -- Mark the Release as modified for build purposes
      PK_RELEASE.SET_RELEASE_MODIFIED(nRtag_id);

   EXCEPTION
      WHEN DUP_VAL_ON_INDEX
      THEN
         raise_application_error (-20000,
                                 'Table already contains a record with the specified OPERATION, RELEASE, and PACKAGE VERSION'
                                 );
      WHEN exc_inst_removed
      THEN
         raise_application_error (-20000,
                                 'Record was probably deleted by the Buildtool during your edit-form session. Please create a new Daemon Instruction.'
                                 );
      WHEN OTHERS
      THEN
         raise;

   END update_daemon_inst;

/*-------------------------------------------------------------------------------------------------------*/
   -- Returns a comma-separated list of operation codes found for a given rtag and pv_id combination
   -- This is for use by the Release Manager Website code.
   --
   FUNCTION daemon_ops_for_rtag_pvid(
      nRtag_id IN NUMBER,
      nPv_id IN NUMBER
   ) RETURN VARCHAR2
   IS
      CURSOR daemon_inst_cur IS
         SELECT di.OP_CODE
         FROM daemon_instructions di
         WHERE di.RTAG_ID = nRtag_id
            AND di.PV_ID = nPv_id;

      daemon_inst_rec   daemon_inst_cur%ROWTYPE;

      sRetList VARCHAR2(4000) := '';

   BEGIN
      OPEN daemon_inst_cur;

      FETCH daemon_inst_cur
      INTO daemon_inst_rec;

      WHILE daemon_inst_cur%FOUND
      LOOP
         sRetList := sRetList || daemon_inst_rec.op_code || ',';

         FETCH daemon_inst_cur
         INTO daemon_inst_rec;
      END LOOP;

      CLOSE daemon_inst_cur;

      RETURN sRetList;
   END daemon_ops_for_rtag_pvid;
/*-------------------------------------------------------------------------------------------------------*/
   -- Returns a comma-separated list of operation codes found for a given rtag
   -- This is for use by the Release Manager Website code.
   --
   FUNCTION daemon_ops_for_rtag(
      nRtag_id IN NUMBER
   ) RETURN VARCHAR2
   IS
      CURSOR daemon_inst_cur IS
         SELECT di.OP_CODE
         FROM daemon_instructions di
         WHERE di.RTAG_ID = nRtag_id;

      daemon_inst_rec   daemon_inst_cur%ROWTYPE;

      sRetList VARCHAR2(4000) := '';

   BEGIN
      OPEN daemon_inst_cur;

      FETCH daemon_inst_cur
      INTO daemon_inst_rec;

      WHILE daemon_inst_cur%FOUND
      LOOP
         sRetList := sRetList || daemon_inst_rec.op_code || ',';

         FETCH daemon_inst_cur
         INTO daemon_inst_rec;
      END LOOP;

      CLOSE daemon_inst_cur;

      RETURN sRetList;
   END daemon_ops_for_rtag;
/*-------------------------------------------------------------------------------------------------------*/
   -- Gets a record from the daemon instruction table that can be carried out now and returns the fields
   -- in the record a daemon will need
   -- The Buildtool should use this to find a job to do for a particular release. It should then call
   -- mark_daemon_inst_in_progress(inst_id) before carrying out the work, and then call
   -- mark_daemon_inst_completed(inst_id) to signal its completion.
   -- Can be called repeatedly to get a full list of all instructions for a release, by passing back in
   -- the instruction ID obtained from the previous call (the 1st call should use 0)
   -- Can be called repeatedly to get a full list of all instructions of a specific op-code value for a release,
   -- by passing back in an op-code value of 0 or higher (use -1 if no op-code filtering is needed)
   -- Returns 1 if a record was found, else 0.
   --
   -- The default value of bExpired (True) will return instructions that have exceeded the scheduled time
  --  A false value will reverse the operation and return instrcutions that have not yet expired
   --
   FUNCTION get_daemon_inst(
      nRtag_id IN NUMBER,
      nInst_id IN OUT NUMBER,
      nOp_code IN OUT NUMBER,
      nPv_id OUT NUMBER,
      nUser_id OUT NUMBER,
      nInProgress OUT NUMBER,
      bExpired IN NUMBER
   ) RETURN NUMBER
   IS
      CURSOR daemon_inst_cur IS
         SELECT di.daemon_instructions_id, di.op_code, di.pv_id ,di.user_id, di.in_progress
           FROM daemon_instructions di
          WHERE di.rtag_id = nRtag_id
            AND di.daemon_instructions_id > nInst_id
            AND (( (bExpired != 0 ) AND (di.scheduled_datetime <= ora_sysdatetime)) OR ( (bExpired = 0) AND (di.scheduled_datetime > ora_sysdatetime) ))
            AND ((nOp_code = -1) OR (nOp_code = di.op_code))
            AND rownum <= 1
       ORDER BY di.daemon_instructions_id;

      daemon_inst_rec   daemon_inst_cur%ROWTYPE;
   BEGIN
      OPEN daemon_inst_cur;

      FETCH daemon_inst_cur
      INTO daemon_inst_rec;

      -- If we found a record, return it.
      IF daemon_inst_cur%FOUND THEN
         nInst_id := daemon_inst_rec.daemon_instructions_id;
         nOp_code := daemon_inst_rec.op_code;
         nPv_id   := daemon_inst_rec.pv_id;
         nUser_id := daemon_inst_rec.user_id;
         IF daemon_inst_rec.in_progress = '1' THEN
            nInProgress := 1;
         ELSE
            nInProgress := 0;
         END IF;
         CLOSE daemon_inst_cur;
         RETURN 1;
      END IF;

      CLOSE daemon_inst_cur;
      RETURN 0;

   END get_daemon_inst;
/*-------------------------------------------------------------------------------------------------------*/
   -- Marks a daemon instruction as being processed by a daemon
   -- The Buildtool should use this before it embarks on the work the instruction commands
   --
   PROCEDURE mark_daemon_inst_in_progress( nInstId IN NUMBER )
   IS
   BEGIN
      UPDATE Daemon_Instructions
      SET in_progress = '1'
      WHERE daemon_instructions_id = nInstId;

   END mark_daemon_inst_in_progress;

/*-------------------------------------------------------------------------------------------------------*/
   -- Once the Buildtool has finished carrying out the daemon instruction, it should call this stored
   -- procedure in order to either delete the instruction or update it in the case where it is a repeating
   -- instruction.
   --
   PROCEDURE mark_daemon_inst_completed( nInstId IN NUMBER )
   IS
      repSecs NUMBER;
      schedDate  DATE;

      CURSOR daemon_inst_cur IS
         SELECT di.REPEAT_SECS AS repSecs, di.SCHEDULED_DATETIME AS schedDate
         FROM daemon_instructions di
         WHERE di.daemon_instructions_id = nInstId;

      daemon_inst_rec   daemon_inst_cur%ROWTYPE;
   BEGIN
      OPEN daemon_inst_cur;

      FETCH daemon_inst_cur
      INTO daemon_inst_rec;

      IF daemon_inst_cur%FOUND THEN

         -- if instruction repeats daily, add 1 day to the scheduled time and update the record
         IF daemon_inst_rec.repSecs = 86400 THEN
            UPDATE Daemon_Instructions
               SET scheduled_datetime = daemon_inst_rec.schedDate + 1,
                  in_progress = '0'
            WHERE daemon_instructions_id = nInstId;
         ELSE
            -- Delete the daemon instruction, we are done with it
            del_daemon_inst(nInstId);
         END IF;
      END IF;

      CLOSE daemon_inst_cur;

   EXCEPTION
      WHEN OTHERS
      THEN
         raise;

   END mark_daemon_inst_completed;
/*-------------------------------------------------------------------------------------------------------*/
   -- This function deletes any old daemon instruction that appears stranded due to a problem that might
   -- have occured during buildtool operation such as might occur if the buildtool or the machine it was
   -- hosted on came down whilst it was processing a daemon instruction.
   PROCEDURE cleanup_stranded_daemon_insts
   IS
   BEGIN
      -- delete records at least two days old
      DELETE FROM daemon_instructions di
      WHERE  (di.scheduled_datetime + 5) <= ora_sysdatetime;

   END cleanup_stranded_daemon_insts;
/*-------------------------------------------------------------------------------------------------------*/
  --This function supersedes function, add_daemon. Done for DEVI-046806
   PROCEDURE add_daemon_config (
      nrtagid           IN   NUMBER,
      nbmcon_id         IN   NUMBER,
      sdaemon_mode      IN   VARCHAR2,
      sgbebuildfilter   IN   VARCHAR2
   )
   IS
      nrecordnumber   NUMBER;
      nrconid         NUMBER;
      sdaemonhostname VARCHAR2(50);
      ngbeid         NUMBER;
   BEGIN
      -- Get RCON_ID
      SELECT seq_rcon_id.NEXTVAL
      INTO nrconid
      FROM DUAL;

      SELECT COUNT (*)
      INTO nrecordnumber
      FROM release_config
      WHERE rtag_id = nrtagid;

      SELECT machine_hostname,gbe_id INTO sdaemonhostname,ngbeid
      FROM build_machine_config
      WHERE bmcon_id = nbmcon_id;

      INSERT INTO release_config
             (rcon_id, rtag_id, daemon_hostname, daemon_mode,
                gbe_id, gbe_buildfilter, bmcon_id)
      VALUES (nrconid, nrtagid, sdaemonhostname, sdaemon_mode,
                ngbeid, sgbebuildfilter, nbmcon_id);

      -- A newly configured daemon should initially be paused (DEVI-047277)
      INSERT INTO run_level
                  (rcon_id, pause)
           VALUES (nrconid, 2);

   END;

/*-------------------------------------------------------------------------------------------------------*/
  --This function supersedes function, update_daemon. Done for DEVI-046806
   PROCEDURE update_daemon_config (
      nrconid           IN   NUMBER,
      nbmcon_id         IN   NUMBER,
      sdaemon_mode      IN   VARCHAR2,
      sgbebuildfilter   IN   VARCHAR2
   )
   IS
      sdaemonhostname VARCHAR2(50);
      ngbeid         NUMBER;
   BEGIN

      SELECT machine_hostname,gbe_id INTO sdaemonhostname,ngbeid
      FROM build_machine_config
      WHERE bmcon_id = nbmcon_id;

      UPDATE release_config
         SET daemon_hostname = sdaemonhostname,
            gbe_id = ngbeid,
            daemon_mode = sdaemon_mode,
            gbe_buildfilter = sgbebuildfilter,
            bmcon_id = nbmcon_id
      WHERE rcon_id = nrconid;
   END;


/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE add_build_machine (
      sdisplay_name          IN   VARCHAR2,
      smachine_hostname      IN   VARCHAR2,
      ngbeid                 IN   NUMBER,
      sdescription           IN   VARCHAR2,
      sactive                IN   CHAR,
      splatform_list         IN  VARCHAR2
   )
   IS
      nrecordnumber   NUMBER;
      nbmcon_id       NUMBER;
      nsPlatformCollector RELMGR_NUMBER_TAB_t := RELMGR_NUMBER_TAB_t();

   BEGIN
      BEGIN
          -- Get BMCON_ID
          SELECT seq_bmcon_id.NEXTVAL INTO nbmcon_id FROM DUAL;

          INSERT INTO build_machine_config(bmcon_id, display_name, machine_hostname,gbe_id,description,active)
                VALUES (nbmcon_id,sdisplay_name,smachine_hostname,ngbeid,sdescription, NVL(sactive,'N'));

       EXCEPTION
          WHEN DUP_VAL_ON_INDEX
          THEN
             raise_application_error (-20000, 'Cannot have duplicate machines.' );
       END;

    DELETE FROM build_platforms_config2
    WHERE bmcon_id = nbmcon_id;

    nsPlatformCollector := in_list_number(splatform_list);
    FOR i IN 1..nsPlatformCollector.count 
    LOOP 
        INSERT INTO build_platforms_config2 (bp_id,bmcon_id) VALUES (nsPlatformCollector(i), nbmcon_id);
    END LOOP;

   END;

/*-------------------------------------------------------------------------------------------------------*/
 PROCEDURE duplicate_daemon_config (
      nrtagid           IN   NUMBER,
      nbmcon_id         IN   NUMBER,
      sdaemonhostname   IN   VARCHAR2,
      ngbe_id           IN   NUMBER,
      sdaemon_mode      IN   VARCHAR2,
      sgbebuildfilter   IN   VARCHAR2
   )
   IS
      nrecordnumber   NUMBER;
      nrconid         NUMBER;
    BEGIN

      -- Get RCON_ID
      SELECT seq_rcon_id.NEXTVAL
      INTO nrconid
      FROM DUAL;

      INSERT INTO release_config
             (rcon_id, rtag_id, daemon_hostname, daemon_mode,
                gbe_id, gbe_buildfilter, bmcon_id)
      VALUES (nrconid, nrtagid, sdaemonhostname, sdaemon_mode,
                ngbe_id, sgbebuildfilter, nbmcon_id);

    -- A newly configured daemon should initially be disabled (DEVI-047277)
      INSERT INTO run_level
                  (rcon_id, pause)
           VALUES (nrconid, 2);

   END;
/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE delete_build_machine (sbmcon_id_list IN VARCHAR2)
   IS
   BEGIN
      DELETE FROM build_machine_config
            WHERE bmcon_id IN (
                     SELECT * FROM THE
                              (SELECT CAST
                                          (in_list_number (sbmcon_id_list) AS relmgr_number_tab_t
                                          )
                                 FROM DUAL
                              ));
   END;


/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE update_build_machine (
      nbmcon_id              IN   NUMBER,
      sdisplay_name          IN   VARCHAR2,
      smachine_hostname      IN   VARCHAR2,
      ngbeid                 IN   NUMBER,
      sdescription           IN   VARCHAR2,
      sactive                IN   CHAR,
      splatform_list         IN  VARCHAR2
   )
   IS
   nsPlatformCollector RELMGR_NUMBER_TAB_t := RELMGR_NUMBER_TAB_t();
   BEGIN
      BEGIN 
          UPDATE build_machine_config
             SET display_name = sdisplay_name,
                 machine_hostname = smachine_hostname,
                 gbe_id = ngbeid,
                 description = sdescription,
                 active = NVL(sactive, 'N')
          WHERE bmcon_id = nbmcon_id;
       EXCEPTION
          WHEN DUP_VAL_ON_INDEX
          THEN
             raise_application_error (-20000,'Cannot have duplicate machines.' );
        END;

    DELETE FROM build_platforms_config2
    WHERE bmcon_id = nbmcon_id;

    nsPlatformCollector := in_list_number(splatform_list);
    FOR i IN 1..nsPlatformCollector.count 
    LOOP 
        INSERT INTO build_platforms_config2 (bp_id,bmcon_id) VALUES (nsPlatformCollector(i), nbmcon_id);
    END LOOP;

   END;

/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE import_daemons ( nSourceRtagId IN NUMBER, nTargetRtagId IN NUMBER, nUserId IN NUMBER  ) IS

   sSourceLocation VARCHAR2(4000);
   sTargetLocation VARCHAR2(4000);
   ProjId NUMBER;
   nIsOpen NUMBER;
   RconId NUMBER;
   bHasDaemons BOOLEAN := FALSE;


   -- this cursor gets the source release daemon configurations, ensuring that the
   -- first record will be the master daemon, and subsequent records will be the slaves.
   CURSOR curSrcReleaseConfigs IS
    SELECT daemon_hostname, gbe_id, gbe_buildfilter, bmcon_id, daemon_mode
     FROM RELEASE_CONFIG rc
    WHERE rc.RTAG_ID = nSourceRtagId
    ORDER BY rc.daemon_mode;
    recSrcReleaseConfigs curSrcReleaseConfigs%ROWTYPE;

    -- this cursor looks for target release daemons
   CURSOR curTgtReleaseConfigs IS
    SELECT rcon_id
     FROM RELEASE_CONFIG rc
    WHERE rc.RTAG_ID = nTargetRtagId;
    recTgtReleaseConfigs curTgtReleaseConfigs%ROWTYPE;

BEGIN
   /*--------------- Business Rules Here -------------------*/
   IF (nSourceRtagId IS NULL) OR (nTargetRtagId IS NULL)
   THEN
      RAISE_APPLICATION_ERROR (-20000, 'Missing some parameters! nSourceRtagId= '|| nSourceRtagId ||', nTargetRtagId='|| nTargetRtagId );
   END IF;

   IF (nSourceRtagId = nTargetRtagId) THEN
      RAISE_APPLICATION_ERROR (-20000, 'Cannot import release contents from same release.' );
   END IF;

   -- Check if Target release is in OPEN mode
  SELECT count(*)  INTO  nIsOpen
    FROM RELEASE_TAGS rt
    WHERE rt.RTAG_ID = nTargetRtagId
    AND rt.OFFICIAL in ('N', 'R', 'C');

  IF (nIsOpen > 1) THEN
    RAISE_APPLICATION_ERROR (-20000, 'Release must be in OPEN mode to import the daemons.' );
  END IF;

   -- check that the target does not have daemons configured
   OPEN curTgtReleaseConfigs;
   FETCH curtgtReleaseConfigs INTO recTgtReleaseConfigs;
   bHasDaemons := curTgtReleaseConfigs%FOUND;
   CLOSE curTgtReleaseConfigs;

  IF bHasDaemons THEN
    RAISE_APPLICATION_ERROR (-20000, 'Release must not have daemons configured' );
  END IF;

   /*-------------------------------------------------------*/

   --Import Release Configuration Information
   OPEN curSrcReleaseConfigs;
   FETCH curSrcReleaseConfigs INTO recSrcReleaseConfigs;

   WHILE curSrcReleaseConfigs%FOUND
   LOOP
      -- add a daemon to the target release
      PK_BUILDAPI.duplicate_daemon_config( nTargetRtagId,
                                     recSrcReleaseConfigs.bmcon_id,
                                     recSrcReleaseConfigs.daemon_hostname,
                                     recSrcReleaseConfigs.gbe_id,
                                     recSrcReleaseConfigs.daemon_mode ,
                                     recSrcReleaseConfigs.gbe_buildfilter );

      FETCH curSrcReleaseConfigs INTO recSrcReleaseConfigs;
   END LOOP;
   CLOSE curSrcReleaseConfigs;


   /* Log Project Action */
   -- Get Source Location
   SELECT pr.PROJ_NAME ||' > '|| rt.RTAG_NAME ||' ['|| rt.RTAG_VERSION ||'.'|| rt.RTAG_LIFE_CYCLE ||']'  INTO sSourceLocation
     FROM RELEASE_TAGS rt,
           PROJECTS pr
    WHERE rt.PROJ_ID = pr.PROJ_ID
      AND rt.RTAG_ID = nSourceRtagId;

   -- Get Target Location
   SELECT pr.PROJ_NAME ||' > '|| rt.RTAG_NAME ||' ['|| rt.RTAG_VERSION ||'.'|| rt.RTAG_LIFE_CYCLE ||']'  INTO sTargetLocation
     FROM RELEASE_TAGS rt,
           PROJECTS pr
    WHERE rt.PROJ_ID = pr.PROJ_ID
      AND rt.RTAG_ID = nTargetRtagId;

   -- Get project id
   SELECT rt.PROJ_ID  INTO  ProjId
     FROM RELEASE_TAGS rt
    WHERE rt.RTAG_ID = nTargetRtagId;

   Log_Project_Action ( ProjId, 'import_daemon_configuration', nUserId, 'SOURCE: '|| sSourceLocation ||'   TARGET: '|| sTargetLocation, nTargetRtagId );
END;

/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE set_build_plan (rtagId IN NUMBER, nStartIndex IN NUMBER, pvList IN VARCHAR2)
   IS
    nPvIdCollector RELMGR_NUMBER_TAB_t := RELMGR_NUMBER_TAB_t();
    SeqNum NUMBER;

   BEGIN

   -- Remove all the old entries, on first usage
   IF nStartIndex = 0 then
    DELETE BUILD_PLAN WHERE RTAG_ID = rtagId;
    SeqNum := 0;
   ELSE
    SELECT COUNT(*) into SeqNum from BUILD_PLAN WHERE RTAG_ID = rtagId;
   END IF;

   -- Set start sequence number
   nPvIdCollector := IN_LIST_NUMBER ( pvList );

   FOR i IN 1..nPvIdCollector.COUNT
   LOOP
      -- Update build plan with order
      INSERT INTO BUILD_PLAN (RTAG_ID, BUILD_ORDER, PV_ID) VALUES (rtagId, SeqNum, nPvIdCollector(i));
      SeqNum := SeqNum + 1;

   END LOOP;
END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE delete_build_platform (bp_id_list IN VARCHAR2)
   IS
   BEGIN
      DELETE FROM build_platforms
            WHERE bp_id IN (
                     SELECT * FROM THE
                              (SELECT CAST
                                          (in_list_number (bp_id_list) AS relmgr_number_tab_t
                                          )
                                 FROM DUAL
                              ));
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE add_build_platform (
      sname                  IN VARCHAR2,
      sdescription           IN VARCHAR2,
      sactive                IN CHAR, 
      sMachType_list         IN VARCHAR2
   )
    IS
      nrecordnumber   NUMBER;
      nbp_id          NUMBER;
      nsMachTypeCollector RELMGR_NUMBER_TAB_t := RELMGR_NUMBER_TAB_t();
   BEGIN
       BEGIN
          -- Get BP_ID
          SELECT seq_build_platforms.NEXTVAL INTO nbp_id FROM DUAL;

          INSERT INTO build_platforms (bp_id, bp_name, bp_description,bp_active)
                VALUES (nbp_id,sname,sdescription, NVL(sactive,'N'));

       EXCEPTION
          WHEN DUP_VAL_ON_INDEX
          THEN
             raise_application_error (-20000,
                                     'Cannot have duplicate platform.'
                                     );
        END;

    DELETE FROM build_platforms_config
    WHERE bp_id = nbp_id;

    nsmachtypecollector := in_list_number(smachtype_list);
    FOR i IN 1..nsmachtypecollector.count 
    LOOP 
        INSERT INTO build_platforms_config (bp_id,gbe_id) VALUES (nbp_id,nsmachtypecollector(i));
    END LOOP;


   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE update_build_platform (
      nbp_id              IN   NUMBER,
      sname               IN   VARCHAR2,
      sdescription        IN   VARCHAR2,
      sactive             IN   CHAR, 
      sMachType_list      IN   VARCHAR2
   )
   IS
   nsMachTypeCollector RELMGR_NUMBER_TAB_t := RELMGR_NUMBER_TAB_t();
BEGIN
    BEGIN
        UPDATE build_platforms
        SET
            bp_name = sname,
            bp_description = sdescription,
            bp_active = nvl(sactive, 'N')
        WHERE
            bp_id = nbp_id;

    EXCEPTION
        WHEN dup_val_on_index THEN
            raise_application_error(-20000, 'Cannot have duplicate platform.');
    END;

    DELETE FROM build_platforms_config
    WHERE bp_id = nbp_id;

    nsmachtypecollector := in_list_number(smachtype_list);
    FOR i IN 1..nsmachtypecollector.count 
    LOOP 
        INSERT INTO build_platforms_config (bp_id,gbe_id) VALUES (nbp_id,nsmachtypecollector(i));
    END LOOP;

END;

--  Insert or delete platforms into the BUILD_INSTANCE_PLATFORMS table
--  nbuildid - BuildId to link with
--  splatforms - CSV list of platforms, If NULL, then the entry will be deleted
--  bClear - Clear all before adding more
--  Returns a CVS list of platforms not known

FUNCTION insert_bi_platforms (
    nbuildid IN NUMBER, splatforms IN VARCHAR2, bClear IN NUMBER
) RETURN VARCHAR2 AS
    idx NUMBER;
    nbpid NUMBER;
    citemcollection relmgr_varchar2_tab_t := relmgr_varchar2_tab_t();
    omessage VARCHAR2(4000);
BEGIN
    IF bClear > 0 THEN
        DELETE FROM build_instance_platforms
        WHERE build_id = nbuildid;
    END IF;

    IF splatforms IS NOT NULL THEN

        citemcollection := in_list_varchar2(splatforms, ',');
        -- dbms_output.put_line(splatforms);
        FOR idx IN 1..citemcollection.count LOOP
            -- dbms_output.put_line(citemcollection(idx));
         BEGIN
            SELECT bp_id
            INTO nbpid
            FROM build_platforms
            WHERE bp_name = citemcollection(idx);
                INSERT INTO build_instance_platforms (
                build_id, bp_id
            ) VALUES (
                nbuildid, nbpid
            );

        EXCEPTION
            WHEN no_data_found THEN
                    -- dbms_output.put_line('No Data found' || citemcollection(idx));
                omessage := omessage
                            || ','
                            || citemcollection(idx);
            WHEN dup_val_on_index THEN
                    -- dbms_output.put_line('DUPLICATE:' || citemcollection(idx));
                NULL;
        END;
        END LOOP;

        omessage := substr(omessage, 2);
        --dbms_output.put_line('NOT FOUND:' || omessage);
    END IF;

    RETURN omessage;
END;

--  Insert or delete platforms into the PACKAGE_VERSION_PLATFORMS table
--  npvid - PvId to link with
--  splatforms - CSV list of platforms, If NULL, then the entry will be deleted
--  bClear - Clear all before adding more
--  Returns a CVS list of platforms not known

FUNCTION insert_pv_platforms (
    npvid IN NUMBER, splatforms IN VARCHAR2, bClear IN NUMBER
) RETURN VARCHAR2 AS
    idx NUMBER;
    nbpid NUMBER;
    citemcollection relmgr_varchar2_tab_t := relmgr_varchar2_tab_t();
    omessage VARCHAR2(4000);
BEGIN
    IF bClear > 0 THEN
        DELETE FROM package_version_platforms
        WHERE pv_id = npvid;
    END IF;

    IF splatforms IS NOT NULL THEN

        citemcollection := in_list_varchar2(splatforms, ',');
        -- dbms_output.put_line(splatforms);
        FOR idx IN 1..citemcollection.count LOOP
            -- dbms_output.put_line(citemcollection(idx));
         BEGIN
            SELECT bp_id
            INTO nbpid
            FROM build_platforms
            WHERE bp_name = citemcollection(idx);
                INSERT INTO package_version_platforms (
                pv_id, bp_id
            ) VALUES (
                npvid, nbpid
            );

        EXCEPTION
            WHEN no_data_found THEN
                    -- dbms_output.put_line('No Data found' || citemcollection(idx));
                omessage := omessage
                            || ','
                            || citemcollection(idx);
            WHEN dup_val_on_index THEN
                    -- dbms_output.put_line('DUPLICATE:' || citemcollection(idx));
                NULL;
        END;
        END LOOP;

        omessage := substr(omessage, 2);
        --dbms_output.put_line('NOT FOUND:' || omessage);
    END IF;

    RETURN omessage;
END;

END pk_buildapi;

/
--------------------------------------------------------
--  DDL for Package Body PK_ENVIRONMENT
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE BODY "RELEASE_MANAGER"."PK_ENVIRONMENT" 
IS

   /*-------------------------------------------------------------------------------------------------------*/
   FUNCTION select_environment_area (cdlock IN package_versions.dlocked%TYPE)
     RETURN NUMBER
   IS
   BEGIN
      /*
     || N - unlocked
     || Y - release and locked
     || P - penging approval
     || A - approved package ready for auto-build
     */
     IF cdlock = 'N' OR cdlock = 'R'
     THEN
       -- WORK IN PROGRESS --
       RETURN 0;
     ELSIF cdlock = 'P' OR cdlock = 'A'
     THEN
       -- PENDING --
       RETURN 1;
     ELSIF cdlock = 'Y'
     THEN
       -- RELEASED --
       RETURN 2;
     ELSE
       -- NOT FOUND --
       raise_application_error
                   (-20000,
                      'Cannot decide where to place package. [cDlock='
                    || cdlock
                    || ']'
                   );
     END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   FUNCTION get_package_area (pvid IN NUMBER, rtagid IN NUMBER)
     RETURN NUMBER
   IS
     envtab   NUMBER         := -1;

     CURSOR curarea
     IS
       SELECT 2 AS envtab
         FROM release_content rc
        WHERE rc.rtag_id = rtagid AND rc.pv_id = pvid
       UNION
       SELECT 0 AS envtab
         FROM work_in_progress wip
        WHERE wip.rtag_id = rtagid AND wip.pv_id = pvid
       UNION
       SELECT 1 AS envtab
         FROM planned pl
        WHERE pl.rtag_id = rtagid AND pl.pv_id = pvid;

     recarea   curarea%ROWTYPE;
   BEGIN
     OPEN curarea;

     FETCH curarea
      INTO recarea;

     IF curarea%FOUND
     THEN
       envtab := recarea.envtab;
     END IF;

     CLOSE curarea;

     RETURN envtab;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   FUNCTION get_view_location (pvid IN NUMBER, rtagid IN NUMBER)
     RETURN NUMBER
   IS
     ispatch   package_versions.dlocked%TYPE;
     viewid   NUMBER                    := -1;

     CURSOR curview
     IS
       SELECT rc.base_view_id AS view_id
         FROM release_content rc
        WHERE rc.rtag_id = rtagid AND rc.pv_id = pvid
       UNION
       SELECT wip.view_id AS view_id
         FROM work_in_progress wip
        WHERE wip.rtag_id = rtagid AND wip.pv_id = pvid
       UNION
       SELECT pl.view_id AS view_id
         FROM planned pl
        WHERE pl.rtag_id = rtagid AND pl.pv_id = pvid;

     recview   curview%ROWTYPE;
   BEGIN
     -- Get dlock state
     SELECT pv.is_patch
      INTO ispatch
      FROM package_versions pv
      WHERE pv.pv_id = pvid;

     -- Decide which view id should package go under.
     IF (ispatch != 'Y') OR (ispatch IS NULL)
     THEN
       -- Get VIEW ID of Package
       OPEN curview;

       FETCH curview
        INTO recview;

       IF curview%FOUND
       THEN
         viewid := recview.view_id;
       ELSE
         raise_application_error
            (-20000,
               'Cannot find view_id to proceed. [PvId='
            || pvid
            || ']. The current version may not exist in the release anymore.'
            );
       END IF;

       CLOSE curview;
     ELSE
       -- Get VIEW ID of Patch (view id of parent package)
       SELECT rc.base_view_id
         INTO viewid
         FROM release_content rc, package_patches ppv
        WHERE rc.rtag_id = rtagid
         AND rc.pv_id = ppv.pv_id
         AND ppv.patch_id = pvid;
     END IF;

     RETURN viewid;
   END;

/*-------------------------------------------------------------------------------------------------------*/
--  Add a package to the specified release
--  Default imode: Will determine the tab ( WIP, PENDING, RELEASE ) to add the package
--  Otherwise will Add the package to the PENDING set
--
   PROCEDURE add_package (
     pvid    IN   NUMBER,
     viewid  IN   NUMBER,
     rtagid  IN   NUMBER,
     userid  IN   NUMBER,
     imode   IN   CHAR default NULL
   )
   IS
     dlocked   package_versions.dlocked%TYPE;
     envtab   NUMBER;
     pendOpr CHAR := 'R';
   BEGIN
     IF can_edit_pkg_in_project (pvid, rtagid) = 1
     THEN
       IF iMode IS NULL THEN
         -- Determine the tab to use based on the package lock state
         -- Get dlock state
         SELECT pv.dlocked
           INTO dlocked
           FROM package_versions pv
          WHERE pv.pv_id = pvid;

         -- Get which area should go under
         envtab := select_environment_area (dlocked);
       ELSE
        -- Assume that the package is to be added to Pending
        envtab := 1;
        pendOpr := 'A';
       END IF;
       -- Log
       --log_action (pvid, 'action', userid, 'Start of Package Add...');

       -- Add Package
       IF envtab = 0
       THEN
         -- WORK IN PROGRESS --
         pk_work_in_progress.add_package (pvid, viewid, rtagid, userid);
       ELSIF envtab = 1
       THEN
         -- PENDING --
         pk_planned.add_package (pvid, viewid, rtagid, userid, pendOpr);
       ELSIF envtab = 2
       THEN
         -- RELEASED --
         -- NOTE: this package will be replaced with matching package
         pk_release.add_package (pvid, viewid, rtagid, userid);
         -- Now do post Release Actions
         pk_release.run_post_actions (pvid, rtagid);
       END IF;

       -- Log
       --log_action (pvid, 'action', userid, 'End of Package Add...');
     END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE add_package_bulk (
     pvidlist   IN   VARCHAR2,
     viewid    IN   NUMBER,
     rtagid    IN   NUMBER,
     userid    IN   NUMBER,
     imode     IN   CHAR DEFAULT NULL
   )
   IS
     nidcollector relmgr_number_tab_t         := relmgr_number_tab_t();
     dlocked      package_versions.dlocked%TYPE;
     pvid         NUMBER;
     envtab       NUMBER;
   BEGIN
     /*--------------- Business Rules Here -------------------*/
     IF (pvidlist IS NULL)
     THEN
       raise_application_error (-20000,
                          'Please select at least one package.'
                         );
     END IF;

/*-------------------------------------------------------*/
     nidcollector := in_list_number (pvidlist);

     FOR i IN 1 .. nidcollector.COUNT
     LOOP
       pvid := nidcollector (i);
       add_package (pvid, viewid, rtagid, userid, imode);
     END LOOP;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE replace_package (
     newpvid  IN   NUMBER,
     oldpvid  IN   NUMBER,
     rtagid   IN   NUMBER,
     userid   IN   NUMBER
   )
   IS
     dlocked      package_versions.dlocked%TYPE;
     viewid       NUMBER;
     envtab       NUMBER;
     ROWCOUNT     NUMBER;
     creleasemode CHAR (1);
     npkgid       NUMBER;
   BEGIN
     /*--------------- Business Rules Here -------------------*/
     -- Check if oldPvId exists. It could have been removed
     SELECT COUNT (pv.pv_id)
       INTO ROWCOUNT
       FROM package_versions pv
      WHERE pv.pv_id = oldpvid;

/*-------------------------------------------------------*/

     /* This procedure is usually used by "History" option in Release Manager */

     -- Get dlock state
     SELECT pv.dlocked
       INTO dlocked
       FROM package_versions pv
      WHERE pv.pv_id = newpvid;

     -- Get VIEW_ID ---
     IF ROWCOUNT = 1
     THEN
       viewid := get_view_location (oldpvid, rtagid);
     ELSE
       -- Set ViewID to default
       viewid := 7;
     END IF;

     -- Get which area should go under
     envtab := select_environment_area (dlocked);
     -- Log
     --log_action (oldpvid, 'action', userid, 'Start of Package Replace...');

     -- Replace package
     IF envtab = 0
     THEN
       -- WORK IN PROGRESS --

       -- Delete old package
       pk_work_in_progress.remove_package (oldpvid, rtagid, userid);

       -- Add new package
       pk_work_in_progress.add_package (newpvid, viewid, rtagid, userid);
     ELSIF envtab = 1
     THEN
       -- PENDING --

       -- Delete old package
       pk_planned.remove_package (oldpvid, rtagid, userid);

       -- Add new package
       pk_planned.add_package (newpvid, viewid, rtagid, userid);
     ELSIF envtab = 2
     THEN
       -- RELEASED --

       -- Replace Package
       pk_release.replace_package(newpvid, oldpvid, rtagid, userid);

       -- Now do post Release Actions
       pk_release.run_post_actions (newpvid, rtagid);
     END IF;

     -- Log
     --log_action (oldpvid, 'action', userid, 'End of Package Replace...');
   END;

/*-------------------------------------------------------------------------------------------------------*/
   FUNCTION remove_package (
     pvid        IN   NUMBER,
     rtagid      IN   NUMBER,
     userid      IN   NUMBER,
     forceremove IN   CHAR
   )
     RETURN NUMBER
   IS
     envtab      NUMBER;
     isused      BOOLEAN;
     recordcount   NUMBER;
   BEGIN
/*--------------- Business Rules Here -------------------*/
/*-------------------------------------------------------*/

     -- Find location of package
     envtab := get_package_area (pvid, rtagid);

     -- Remove Package
     IF envtab = 0
     THEN
       -- WORK IN PROGRESS --
       -- Delete package
       pk_work_in_progress.remove_package (pvid, rtagid, userid);

       RETURN 0;
     ELSIF envtab = 1
     THEN
       -- PENDING --
       -- Delete package
       pk_planned.remove_package (pvid, rtagid, userid);

       RETURN 0;
     ELSIF envtab = 2
     THEN
       -- RELEASED --

       -- Check if is used by other packages
       isused := TRUE;

       IF forceremove = 'N'
       THEN
          select count(dpv.PKG_ID) INTO recordcount from
          (SELECT  rc.pv_id
          FROM RELEASE_CONTENT rc, PEGGED_VERSIONS peg
            WHERE rc.rtag_id = rtagid
            AND peg.RTAG_ID(+) = rc.RTAG_ID
            AND peg.PV_ID(+) = rc.PV_ID
            AND peg.rtag_id is null
            AND rc.SDKTAG_ID is null
            ) arc,
          PACKAGE_DEPENDENCIES dep,
          PACKAGE_VERSIONS pv,
          PACKAGE_VERSIONS dpv,
          PACKAGE_VERSIONS bpv
          where dep.PV_ID = arc.pv_id
          AND dep.pv_id = pv.pv_id
          AND dep.dpv_id = dpv.PV_ID
          AND dpv.PKG_ID = bpv.PKG_ID
          AND NVL(dpv.V_EXT, '.NULL') = NVL(bpv.V_EXT, '.NULL')
          AND bpv.pv_id = pvid;

         IF recordcount > 0
         THEN
            RETURN 1;               -- Return 1 as package being used
         ELSE
            isused := FALSE;
         END IF;
       END IF;

       IF forceremove = 'Y' OR NOT isused
       THEN
         -- Delete old package
         pk_release.remove_package (pvid, rtagid, userid);

         -- Delete old package's pegging info
         DELETE FROM PEGGED_VERSIONS pegv WHERE pegv.RTAG_ID = rtagid AND pegv.PV_ID = pvid;

         -- Delete old package's advisory ripple info
         DELETE FROM ADVISORY_RIPPLE avr WHERE avr.RTAG_ID = rtagid AND avr.PV_ID = pvid;

         -- Now do post Release Actions
         pk_release.run_post_actions (pvid, rtagid);
         RETURN 0;
       END IF;
     END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   -- DEVI-45275 added the return of the new "operation" column in the recordset.
PROCEDURE get_environment_items (
     viewtype         IN      NUMBER,
     userid           IN      NUMBER,
     rtagid           IN      NUMBER,
     sviewidshowlist  IN      VARCHAR2,
     ntruerecordcount OUT     NUMBER,
     recordset        OUT     typecur
   )
   IS
   BEGIN
     -- Get true record count because views can give false count
     SELECT COUNT (pl.pv_id)
      INTO ntruerecordcount
      FROM environment_view pl
      WHERE pl.rtag_id = rtagid;

     IF viewtype = 1
     THEN
       /*--- GUEST VIEW ---*/
       OPEN recordset FOR
         SELECT   *
            FROM (
                 /* Base Views collapsed */
                 SELECT DISTINCT vi.view_id, vi.view_name,
                             TO_NUMBER (NULL) AS pkg_state,
                             TO_NUMBER (NULL) AS deprecated_state,
                             TO_NUMBER (NULL) AS pv_id,
                             NULL AS pkg_name, NULL AS pkg_version,
                             NULL AS dlocked, NULL AS pv_description,
                             rel.operation
                         FROM environment_view rel, views vi
                        WHERE rel.view_id = vi.view_id
                          AND rtag_id = rtagid
                          AND rel.view_id NOT IN (
                               SELECT *
                                 FROM THE
                                       (SELECT CAST
                                               (in_list_number
                                                  (sviewidshowlist
                                                  ) AS relmgr_number_tab_t
                                               )
                                         FROM DUAL
                                       ))
                 UNION
                 /* Base Views expanded */
                 SELECT vi.view_id, vi.view_name,
                      DECODE (rel.pkg_state,
                            NULL, 0,
                            rel.pkg_state
                           ) AS pkg_state,
                      rel.deprecated_state, pv.pv_id, pkg.pkg_name,
                      pv.pkg_version, pv.dlocked, pv.pv_description,
                      rel.operation
                  FROM environment_view rel,
                      PACKAGES pkg,
                      package_versions pv,
                      views vi
                  WHERE pv.pkg_id = pkg.pkg_id
                   AND rel.pv_id = pv.pv_id
                   AND rel.view_id = vi.view_id
                   AND rel.view_id IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                   AND rtag_id = rtagid) ord
         ORDER BY UPPER (ord.view_name), UPPER (ord.pkg_name);
     ELSIF viewtype = 2
     THEN
       /*--- PERSONAL VIEW ---*/
       OPEN recordset FOR
         SELECT   *
            FROM (
                 /* Base Views collapsed */
                 SELECT DISTINCT vi.view_id, vi.view_name,
                             TO_NUMBER (NULL) AS pkg_state,
                             TO_NUMBER (NULL) AS deprecated_state,
                             TO_NUMBER (NULL) AS pv_id,
                             NULL AS pkg_name, NULL AS pkg_version,
                             NULL AS dlocked, NULL AS pv_description,
                             rel.operation
                         FROM environment_view rel,
                             view_settings vs,
                             views vi
                        WHERE rel.view_id = vi.view_id
                          AND vs.view_id = rel.view_id
                          AND vs.user_id = userid
                          AND rtag_id = rtagid
                          AND rel.view_id NOT IN (
                               SELECT *
                                 FROM THE
                                       (SELECT CAST
                                               (in_list_number
                                                  (sviewidshowlist
                                                  ) AS relmgr_number_tab_t
                                               )
                                         FROM DUAL
                                       ))
                 UNION
                 /* Base Views expanded */
                 SELECT vi.view_id, vi.view_name,
                      DECODE (rel.pkg_state,
                            NULL, 0,
                            rel.pkg_state
                           ) AS pkg_state,
                      rel.deprecated_state, pv.pv_id, pkg.pkg_name,
                      pv.pkg_version, pv.dlocked, pv.pv_description,
                      rel.operation
                  FROM environment_view rel,
                      PACKAGES pkg,
                      package_versions pv,
                      views vi,
                      view_settings vs
                  WHERE pv.pkg_id = pkg.pkg_id
                   AND rel.pv_id = pv.pv_id
                   AND rel.view_id = vi.view_id
                   AND vs.view_id = vi.view_id
                   AND vs.user_id = userid
                   AND rel.view_id IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                   AND rtag_id = rtagid
                 UNION
                 /* Private Views collapsed */
                 SELECT vi.view_id, vi.view_name,
                      TO_NUMBER (NULL) AS pkg_state,
                      TO_NUMBER (NULL) AS deprecated_state,
                      TO_NUMBER (NULL) AS pv_id, NULL AS pkg_name,
                      NULL AS pkg_version, NULL AS dlocked,
                      NULL AS pv_description,
                      rel.operation
                  FROM view_settings vs,
                      view_def vd,
                      views vi,
                      environment_view rel,
                      package_versions pv
                  WHERE vs.view_id = vi.view_id
                   AND rel.pv_id = pv.pv_id
                   AND vd.pkg_id = pv.pkg_id
                   AND vd.view_id = vi.view_id
                   AND vi.base_view = 'N'
                   AND rel.rtag_id = rtagid
                   AND vs.user_id = userid
                   AND vi.view_id NOT IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                 UNION
                 /* Private Views expanded */
                 SELECT vi.view_id, vi.view_name,
                      DECODE (rel.pkg_state,
                            NULL, 0,
                            rel.pkg_state
                           ) AS pkg_state,
                      rel.deprecated_state, pv.pv_id, pkg.pkg_name,
                      pv.pkg_version, pv.dlocked, pv.pv_description,
                      rel.operation
                  FROM users usr,
                      view_settings vs,
                      view_def vd,
                      views vi,
                      environment_view rel,
                      PACKAGES pkg,
                      package_versions pv
                  WHERE vs.user_id = usr.user_id
                   AND vs.view_id = vi.view_id
                   AND vd.view_id = vi.view_id
                   AND pv.pkg_id = pkg.pkg_id
                   AND rel.pv_id = pv.pv_id
                   AND rel.rtag_id = rtagid
                   AND vd.pkg_id = pkg.pkg_id
                   AND vi.base_view = 'N'
                   AND vi.view_id IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                   AND usr.user_id = userid) ord
         ORDER BY UPPER (ord.view_name), UPPER (ord.pkg_name);
     END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/
  PROCEDURE get_released_items (
     viewtype         IN      NUMBER,
     userid           IN      NUMBER,
     rtagid           IN      NUMBER,
     sviewidshowlist  IN      VARCHAR2,
     ntruerecordcount OUT     NUMBER,
     recordset        OUT     typecur
   )
   IS
   BEGIN
     -- Get true record count because views can give false count
     SELECT COUNT (pl.pv_id)
      INTO ntruerecordcount
      FROM environment_view pl
      WHERE pl.rtag_id = rtagid;

     IF viewtype = 1
     THEN
       /*--- GUEST VIEW ---*/
       OPEN recordset FOR
         SELECT   *
            FROM (
                 /* Base Views collapsed */
                 SELECT DISTINCT vi.view_id, vi.view_name,
                             TO_NUMBER (NULL) AS pkg_state,
                             TO_NUMBER (NULL) AS deprecated_state,
                             TO_NUMBER (NULL) AS pv_id,
                             NULL AS pkg_name, NULL AS pkg_version,
                             NULL AS dlocked, NULL AS pv_description,
                             rel.operation
                         FROM environment_view rel, views vi
                        WHERE rel.view_id = vi.view_id
                          AND rel.env_area = 2
                          AND rtag_id = rtagid
                          AND rel.view_id NOT IN (
                               SELECT *
                                 FROM THE
                                       (SELECT CAST
                                               (in_list_number
                                                  (sviewidshowlist
                                                  ) AS relmgr_number_tab_t
                                               )
                                         FROM DUAL
                                       ))
                 UNION
                 /* Base Views expanded */
                 SELECT vi.view_id, vi.view_name,
                     rel.pkg_state,
                      rel.deprecated_state, pv.pv_id, pkg.pkg_name,
                      pv.pkg_version, pv.dlocked, pv.pv_description,
                      rel.operation
                  FROM environment_view rel,
                      PACKAGES pkg,
                      package_versions pv,
                      views vi
                  WHERE pv.pkg_id = pkg.pkg_id
                   AND rel.pv_id = pv.pv_id
                   AND rel.env_area = 2
                   AND rel.view_id = vi.view_id
                   AND rel.view_id IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                   AND rtag_id = rtagid) ord
         ORDER BY UPPER (ord.view_name), UPPER (ord.pkg_name);
     ELSIF viewtype = 2
     THEN
       /*--- PERSONAL VIEW ---*/
       OPEN recordset FOR
         SELECT   *
            FROM (
                 /* Base Views collapsed */
                 SELECT DISTINCT vi.view_id, vi.view_name,
                             TO_NUMBER (NULL) AS pkg_state,
                             TO_NUMBER (NULL) AS deprecated_state,
                             TO_NUMBER (NULL) AS pv_id,
                             NULL AS pkg_name, NULL AS pkg_version,
                             NULL AS dlocked, NULL AS pv_description,
                             rel.operation
                         FROM environment_view rel,
                             view_settings vs,
                             views vi
                        WHERE rel.view_id = vi.view_id
                          AND rel.env_area = 2
                          AND vs.view_id = rel.view_id
                          AND vs.user_id = userid
                          AND rtag_id = rtagid
                          AND rel.view_id NOT IN (
                               SELECT *
                                 FROM THE
                                       (SELECT CAST
                                               (in_list_number
                                                  (sviewidshowlist
                                                  ) AS relmgr_number_tab_t
                                               )
                                         FROM DUAL
                                       ))
                 UNION
                 /* Base Views expanded */
                 SELECT vi.view_id, vi.view_name,
                        rel.pkg_state,
                      rel.deprecated_state, pv.pv_id, pkg.pkg_name,
                      pv.pkg_version, pv.dlocked, pv.pv_description,
                      rel.operation
                  FROM environment_view rel,
                      PACKAGES pkg,
                      package_versions pv,
                      views vi,
                      view_settings vs
                  WHERE pv.pkg_id = pkg.pkg_id
                   AND rel.pv_id = pv.pv_id
                   AND rel.view_id = vi.view_id
                   AND rel.env_area = 2
                   AND vs.view_id = vi.view_id
                   AND vs.user_id = userid
                   AND rel.view_id IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                   AND rtag_id = rtagid
                 UNION
                 /* Private Views collapsed */
                 SELECT vi.view_id, vi.view_name,
                      TO_NUMBER (NULL) AS pkg_state,
                      TO_NUMBER (NULL) AS deprecated_state,
                      TO_NUMBER (NULL) AS pv_id, NULL AS pkg_name,
                      NULL AS pkg_version, NULL AS dlocked,
                      NULL AS pv_description,
                      rel.operation
                  FROM view_settings vs,
                      view_def vd,
                      views vi,
                      environment_view rel,
                      package_versions pv
                  WHERE vs.view_id = vi.view_id
                   AND rel.env_area = 2
                   AND rel.pv_id = pv.pv_id
                   AND vd.pkg_id = pv.pkg_id
                   AND vd.view_id = vi.view_id
                   AND vi.base_view = 'N'
                   AND rel.rtag_id = rtagid
                   AND vs.user_id = userid
                   AND vi.view_id NOT IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                 UNION
                 /* Private Views expanded */
                 SELECT vi.view_id, vi.view_name,
                      rel.pkg_state,
                      rel.deprecated_state, pv.pv_id, pkg.pkg_name,
                      pv.pkg_version, pv.dlocked, pv.pv_description,
                      rel.operation
                  FROM users usr,
                      view_settings vs,
                      view_def vd,
                      views vi,
                      environment_view rel,
                      PACKAGES pkg,
                      package_versions pv
                  WHERE vs.user_id = usr.user_id
                   AND vs.view_id = vi.view_id
                   AND rel.env_area = 2
                   AND vd.view_id = vi.view_id
                   AND pv.pkg_id = pkg.pkg_id
                   AND rel.pv_id = pv.pv_id
                   AND rel.rtag_id = rtagid
                   AND vd.pkg_id = pkg.pkg_id
                   AND vi.base_view = 'N'
                   AND vi.view_id IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                   AND usr.user_id = userid) ord
         ORDER BY UPPER (ord.view_name), UPPER (ord.pkg_name);
     END IF;
   END;


/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE get_work_in_progress_items (
     viewtype         IN      NUMBER,
     userid           IN      NUMBER,
     rtagid           IN      NUMBER,
     sviewidshowlist  IN      VARCHAR2,
     ntruerecordcount OUT     NUMBER,
     recordset        OUT     typecur
   )
   IS
   BEGIN
     -- Get true record count because views can give false count
     SELECT COUNT (wip.pv_id)
      INTO ntruerecordcount
      FROM work_in_progress wip
      WHERE wip.rtag_id = rtagid;

     IF viewtype = 1
     THEN
       /*--- GUEST VIEW ---*/
       OPEN recordset FOR
         SELECT   *
            FROM (
                 /* Base Views collapsed */
                 SELECT DISTINCT vi.view_id, vi.view_name,
                             TO_NUMBER (NULL) AS pkg_state,
                             TO_NUMBER (NULL) AS deprecated_state,
                             TO_NUMBER (NULL) AS pv_id,
                             NULL AS pkg_name, NULL AS pkg_version,
                             NULL AS dlocked, NULL AS pv_description
                         FROM work_in_progress rel, views vi
                        WHERE rel.view_id = vi.view_id
                          AND rtag_id = rtagid
                          AND rel.view_id NOT IN (
                               SELECT *
                                 FROM THE
                                       (SELECT CAST
                                               (in_list_number
                                                  (sviewidshowlist
                                                  ) AS relmgr_number_tab_t
                                               )
                                         FROM DUAL
                                       ))
                 UNION
                 /* Base Views expanded */
                 SELECT vi.view_id, vi.view_name, 0 AS pkg_state,

                      --rel.pkg_state,
                      TO_NUMBER (NULL) AS deprecated_state, pv.pv_id,
                      pkg.pkg_name, pv.pkg_version, pv.dlocked,
                      pv.pv_description
                  FROM work_in_progress rel,
                      PACKAGES pkg,
                      package_versions pv,
                      views vi
                  WHERE pv.pkg_id = pkg.pkg_id
                   AND rel.pv_id = pv.pv_id
                   AND rel.view_id = vi.view_id
                   AND rel.view_id IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                   AND rtag_id = rtagid) ord
         ORDER BY UPPER (ord.view_name), UPPER (ord.pkg_name);
     ELSIF viewtype = 2
     THEN
       /*--- PERSONAL VIEW ---*/
       OPEN recordset FOR
         SELECT   *
            FROM (
                 /* Base Views collapsed */
                 SELECT DISTINCT vi.view_id, vi.view_name,
                             TO_NUMBER (NULL) AS pkg_state,
                             TO_NUMBER (NULL) AS deprecated_state,
                             TO_NUMBER (NULL) AS pv_id,
                             NULL AS pkg_name, NULL AS pkg_version,
                             NULL AS dlocked, NULL AS pv_description
                         FROM work_in_progress rel,
                             view_settings vs,
                             views vi
                        WHERE rel.view_id = vi.view_id
                          AND vs.view_id = rel.view_id
                          AND vs.user_id = userid
                          AND rtag_id = rtagid
                          AND rel.view_id NOT IN (
                               SELECT *
                                 FROM THE
                                       (SELECT CAST
                                               (in_list_number
                                                  (sviewidshowlist
                                                  ) AS relmgr_number_tab_t
                                               )
                                         FROM DUAL
                                       ))
                 UNION
                 /* Base Views expanded */
                 SELECT vi.view_id, vi.view_name, 0 AS pkg_state,

                      --rel.pkg_state,
                      TO_NUMBER (NULL) AS deprecated_state, pv.pv_id,
                      pkg.pkg_name, pv.pkg_version, pv.dlocked,
                      pv.pv_description
                  FROM work_in_progress rel,
                      PACKAGES pkg,
                      package_versions pv,
                      views vi,
                      view_settings vs
                  WHERE pv.pkg_id = pkg.pkg_id
                   AND rel.pv_id = pv.pv_id
                   AND rel.view_id = vi.view_id
                   AND vs.view_id = vi.view_id
                   AND vs.user_id = userid
                   AND rel.view_id IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                   AND rtag_id = rtagid
                 UNION
                 /* Private Views collapsed */
                 SELECT vi.view_id, vi.view_name,
                      TO_NUMBER (NULL) AS pkg_state,
                      TO_NUMBER (NULL) AS deprecated_state,
                      TO_NUMBER (NULL) AS pv_id, NULL AS pkg_name,
                      NULL AS pkg_version, NULL AS dlocked,
                      NULL AS pv_description
                  FROM view_settings vs,
                      view_def vd,
                      views vi,
                      work_in_progress rel,
                      package_versions pv
                  WHERE vs.view_id = vi.view_id
                   AND rel.pv_id = pv.pv_id
                   AND vd.pkg_id = pv.pkg_id
                   AND vd.view_id = vi.view_id
                   AND vi.base_view = 'N'
                   AND rel.rtag_id = rtagid
                   AND vs.user_id = userid
                   AND vi.view_id NOT IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                 UNION
                 /* Private Views expanded */
                 SELECT vi.view_id, vi.view_name, 0 AS pkg_state,

                      --rel.pkg_state,
                      TO_NUMBER (NULL) AS deprecated_state, pv.pv_id,
                      pkg.pkg_name, pv.pkg_version, pv.dlocked,
                      pv.pv_description
                  FROM users usr,
                      view_settings vs,
                      view_def vd,
                      views vi,
                      work_in_progress rel,
                      PACKAGES pkg,
                      package_versions pv
                  WHERE vs.user_id = usr.user_id
                   AND vs.view_id = vi.view_id
                   AND vd.view_id = vi.view_id
                   AND pv.pkg_id = pkg.pkg_id
                   AND rel.pv_id = pv.pv_id
                   AND rel.rtag_id = rtagid
                   AND vd.pkg_id = pkg.pkg_id
                   AND vi.base_view = 'N'
                   AND vi.view_id IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                   AND usr.user_id = userid) ord
         ORDER BY UPPER (ord.view_name), UPPER (ord.pkg_name);
     END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   -- DEVI-45275 added the return of the new "operation" column in the recordset.

PROCEDURE get_pending_items (
     viewtype         IN      NUMBER,
     userid           IN      NUMBER,
     rtagid           IN      NUMBER,
     sviewidshowlist  IN      VARCHAR2,
     ntruerecordcount OUT     NUMBER,
     recordset        OUT     typecur
   )
   IS
   BEGIN
     -- Get true record count because views can give false count
     SELECT COUNT (pl.pv_id)
      INTO ntruerecordcount
      FROM environment_view pl
      WHERE pl.rtag_id = rtagid;

     IF viewtype = 1
     THEN
       /*--- GUEST VIEW ---*/
       OPEN recordset FOR
         SELECT   *
            FROM (
                 /* Base Views collapsed */
                 SELECT DISTINCT vi.view_id, vi.view_name,
                             TO_NUMBER (NULL) AS pkg_state,
                             TO_NUMBER (NULL) AS deprecated_state,
                             TO_NUMBER (NULL) AS pv_id,
                             NULL AS pkg_name, NULL AS pkg_version,
                             NULL AS dlocked, NULL AS pv_description,
                             rel.operation
                         FROM environment_view rel, views vi
                        WHERE rel.view_id = vi.view_id
                          AND rel.env_area = 1
                          AND rtag_id = rtagid
                          AND rel.view_id NOT IN (
                               SELECT *
                                 FROM THE
                                       (SELECT CAST
                                               (in_list_number
                                                  (sviewidshowlist
                                                  ) AS relmgr_number_tab_t
                                               )
                                         FROM DUAL
                                       ))
                 UNION
                 /* Base Views expanded */
                 SELECT vi.view_id, vi.view_name,
                     rel.pkg_state,
                      rel.deprecated_state, pv.pv_id, pkg.pkg_name,
                      pv.pkg_version, pv.dlocked, pv.pv_description,
                      rel.operation
                  FROM environment_view rel,
                      PACKAGES pkg,
                      package_versions pv,
                      views vi
                  WHERE pv.pkg_id = pkg.pkg_id
                   AND rel.pv_id = pv.pv_id
                   AND rel.env_area = 1
                   AND rel.view_id = vi.view_id
                   AND rel.view_id IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                   AND rtag_id = rtagid) ord
         ORDER BY UPPER (ord.view_name), UPPER (ord.pkg_name);
     ELSIF viewtype = 2
     THEN
       /*--- PERSONAL VIEW ---*/
       OPEN recordset FOR
         SELECT   *
            FROM (
                 /* Base Views collapsed */
                 SELECT DISTINCT vi.view_id, vi.view_name,
                             TO_NUMBER (NULL) AS pkg_state,
                             TO_NUMBER (NULL) AS deprecated_state,
                             TO_NUMBER (NULL) AS pv_id,
                             NULL AS pkg_name, NULL AS pkg_version,
                             NULL AS dlocked, NULL AS pv_description,
                             rel.operation
                         FROM environment_view rel,
                             view_settings vs,
                             views vi
                        WHERE rel.view_id = vi.view_id
                          AND rel.env_area = 1
                          AND vs.view_id = rel.view_id
                          AND vs.user_id = userid
                          AND rtag_id = rtagid
                          AND rel.view_id NOT IN (
                               SELECT *
                                 FROM THE
                                       (SELECT CAST
                                               (in_list_number
                                                  (sviewidshowlist
                                                  ) AS relmgr_number_tab_t
                                               )
                                         FROM DUAL
                                       ))
                 UNION
                 /* Base Views expanded */
                 SELECT vi.view_id, vi.view_name,
                        rel.pkg_state,
                      rel.deprecated_state, pv.pv_id, pkg.pkg_name,
                      pv.pkg_version, pv.dlocked, pv.pv_description,
                      rel.operation
                  FROM environment_view rel,
                      PACKAGES pkg,
                      package_versions pv,
                      views vi,
                      view_settings vs
                  WHERE pv.pkg_id = pkg.pkg_id
                   AND rel.pv_id = pv.pv_id
                   AND rel.view_id = vi.view_id
                   AND rel.env_area = 1
                   AND vs.view_id = vi.view_id
                   AND vs.user_id = userid
                   AND rel.view_id IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                   AND rtag_id = rtagid
                 UNION
                 /* Private Views collapsed */
                 SELECT vi.view_id, vi.view_name,
                      TO_NUMBER (NULL) AS pkg_state,
                      TO_NUMBER (NULL) AS deprecated_state,
                      TO_NUMBER (NULL) AS pv_id, NULL AS pkg_name,
                      NULL AS pkg_version, NULL AS dlocked,
                      NULL AS pv_description,
                      rel.operation
                  FROM view_settings vs,
                      view_def vd,
                      views vi,
                      environment_view rel,
                      package_versions pv
                  WHERE vs.view_id = vi.view_id
                   AND rel.env_area = 1
                   AND rel.pv_id = pv.pv_id
                   AND vd.pkg_id = pv.pkg_id
                   AND vd.view_id = vi.view_id
                   AND vi.base_view = 'N'
                   AND rel.rtag_id = rtagid
                   AND vs.user_id = userid
                   AND vi.view_id NOT IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                 UNION
                 /* Private Views expanded */
                 SELECT vi.view_id, vi.view_name,
                      rel.pkg_state,
                      rel.deprecated_state, pv.pv_id, pkg.pkg_name,
                      pv.pkg_version, pv.dlocked, pv.pv_description,
                      rel.operation
                  FROM users usr,
                      view_settings vs,
                      view_def vd,
                      views vi,
                      environment_view rel,
                      PACKAGES pkg,
                      package_versions pv
                  WHERE vs.user_id = usr.user_id
                   AND vs.view_id = vi.view_id
                   AND rel.env_area = 1
                   AND vd.view_id = vi.view_id
                   AND pv.pkg_id = pkg.pkg_id
                   AND rel.pv_id = pv.pv_id
                   AND rel.rtag_id = rtagid
                   AND vd.pkg_id = pkg.pkg_id
                   AND vi.base_view = 'N'
                   AND vi.view_id IN (
                        SELECT *
                          FROM THE
                                (SELECT CAST
                                        (in_list_number
                                               (sviewidshowlist) AS relmgr_number_tab_t
                                        )
                                  FROM DUAL
                                ))
                   AND usr.user_id = userid) ord
         ORDER BY UPPER (ord.view_name), UPPER (ord.pkg_name);
     END IF;
   END;


/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE get_view_content (
     rtagid     IN      NUMBER,
     viewid     IN      NUMBER,
     recordset OUT     typecur
   )
   IS
     isbaseview   CHAR (1);
   BEGIN
     -- Check if the view is BASE VIEW
     SELECT vi.base_view
      INTO isbaseview
      FROM views vi
      WHERE vi.view_id = viewid;

     IF (IsBaseView IN ('Y', 'S'))
     THEN
       -- Get Base view content
       OPEN recordset FOR
         SELECT   DECODE (rel.pkg_state,
                      NULL, 0,
                      rel.pkg_state
                     ) AS pkg_state,
                rel.deprecated_state, pv.pv_id, pkg.pkg_name,
                pv.pkg_version, pv.dlocked, pv.pv_description,
                pv.build_type,
                rel.operation
            FROM environment_view rel, 
                PACKAGES pkg,
                package_versions pv
            WHERE pv.pkg_id = pkg.pkg_id
             AND rel.pv_id = pv.pv_id
             AND rel.view_id = viewid
             AND rel.rtag_id = rtagid
         ORDER BY UPPER (pkg.pkg_name);
     ELSE
       -- Get non base view content
       OPEN recordset FOR
         SELECT   DECODE (rel.pkg_state,
                      NULL, 0,
                      rel.pkg_state
                     ) AS pkg_state,
                rel.deprecated_state, pv.pv_id, pkg.pkg_name,
                pv.pkg_version, pv.dlocked, pv.pv_description,
                pv.build_type,
                rel.operation
            FROM environment_view rel,
                PACKAGES pkg,
                package_versions pv,
                view_def vd
            WHERE pv.pkg_id = pkg.pkg_id
             AND rel.pv_id = pv.pv_id
             AND rel.rtag_id = rtagid
             AND vd.view_id = viewid
             AND vd.pkg_id = pv.pkg_id
         ORDER BY UPPER (pkg.pkg_name);
     END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   FUNCTION get_package_view (pvid IN NUMBER, rtagid IN NUMBER)
     RETURN NUMBER
   IS
     envtab           NUMBER;
     returnvalue      NUMBER;
     return_not_found NUMBER := -1;
   BEGIN
     envtab := get_package_area (pvid, rtagid);

     IF envtab = 0
     THEN
       -- WORK IN PROGRESS --
       returnvalue := pk_work_in_progress.get_package_view (pvid, rtagid);
     ELSIF envtab = 1
     THEN
       -- PENDING --
       returnvalue := pk_planned.get_package_view (pvid, rtagid);
     ELSIF envtab = 2
     THEN
       -- RELEASED --
       returnvalue := pk_release.get_package_view (pvid, rtagid);
     ELSE
       -- This may be a Patch not located anywhere but unlocked
       returnvalue := return_not_found;
     END IF;

     RETURN returnvalue;
   END;

/*-------------------------------------------------------------------------------------------------------*/
  PROCEDURE make_release (
     pvid          IN   NUMBER,                         -- NEW  PKG pvid
     rtagid        IN   NUMBER,                         -- Release Id
     userid        IN   NUMBER                          -- User performing Release
   )
   IS
     viewid        NUMBER;
     envtab        NUMBER;
     ispatch       CHAR (1) := NULL;
     buildtype     CHAR (1) := NULL;
   BEGIN
     -- Check if package is patch
     SELECT pv.is_patch, pv.build_type
      INTO ispatch, buildtype
      FROM package_versions pv
      WHERE pv.pv_id = pvid;

     -- Get ViewId
     viewid := get_package_view (pvid, rtagid);
     -- Remove from current area
     envtab := pk_environment.get_package_area (pvid, rtagid);

     -- Make sure that package was in work-in-progress or pending before makeing it release
     -- Exclude patches, ripple builds
     IF (envtab < 0)
     THEN
       -- Not found in work-in-progress or pending
       IF (ispatch IS NULL) AND (buildtype = 'M')
       THEN
         raise_application_error (-20000,
                            'This package cannot be released here.'
                           );
       END IF;
     END IF;

     -- Log
     --log_action (pvid, 'action', userid, 'Start of Make Package Release...');

     IF envtab = 0
     THEN
       -- WORK IN PROGRESS --
       pk_work_in_progress.remove_package (pvid, rtagid, userid);
     ELSIF envtab = 1
     THEN
       -- PENDING --
       pk_planned.remove_package (pvid, rtagid, userid);
     END IF;

     -- Change package state
     -- Set dlocked state to mark the package a 'Released and Locked'
     pk_package.change_state (pvid, 'Y', userid);

     -- Make sure it is valid BASE VIEW
     IF viewid < 1
     THEN
       viewid := 7;                     -- This is default base view
     END IF;

     IF (ispatch IS NULL)
     THEN
       -- Add (Replace) package to new area
       pk_release.add_package (pvid, viewid, rtagid, userid);
     END IF;

     -- Now do post Release Actions
     pk_release.run_post_actions (pvid, rtagid);

     -- The release has changed and there may now be invalid rtag_id/pv_id combinations in
     -- the DO_NOT_RIPPLE and ADVISORY_RIPPLE Tables so perform a clean-up operation upon them.
     clean_do_not_ripple(rtagid);
     clean_advisory_ripple(rtagid);

     -- Log
     --log_action (pvid, 'action', userid, 'End of Make Package Release...');
   END;

/*-------------------------------------------------------------------------------------------------------*/
  --  Release a specified package into a specified release
  --
  --  Similar to 'make_release', but it attempts to handle the case where a package-version
  --  is being replaced with one with a different package-suffix, but it doesn't
  --  handle all the cases well.
  --
  --  The current build system cannot do this automatically - yet
  --
  --
   PROCEDURE auto_make_release (
     pvid          IN   NUMBER,                         -- NEW  PKG pvid
     rtagid        IN   NUMBER,                         -- Release Id
     userid        IN   NUMBER,                         -- User performing Release
     vext          IN   package_versions.v_ext%TYPE,    -- Package Extension for original pkg
     ssv_ext       IN   package_versions.v_ext%TYPE,    -- Package Extension for new package
     clonefrompvid IN   NUMBER                          -- PVID of Original
   )
   IS
     viewid        NUMBER;
     envtab        NUMBER;

     clone_removal NUMBER := 0;
     clone_viewid  NUMBER := -1;
     clone_envtab  NUMBER := -1;

     ispatch       CHAR (1) := NULL;
     buildtype     CHAR (1) := NULL;

   BEGIN
     -- Check if package is patch
     SELECT pv.is_patch, pv.build_type
      INTO ispatch, buildtype
      FROM package_versions pv
      WHERE pv.pv_id = pvid;

     --
     -- Determine the viewid and environment for the new package
     --
     viewid := get_package_view (pvid, rtagid);
     envtab := pk_environment.get_package_area (pvid, rtagid);

     --
     -- If changing pkgExt, then we need to delete the orig package, not just replace it
     --
     IF (clonefrompvid is NOT NULL) AND (vext <> ssv_ext)
     THEN
        clone_removal := 1;
        clone_viewid := get_package_view (clonefrompvid, rtagid);
        clone_envtab := pk_environment.get_package_area (clonefrompvid, rtagid);
     END IF;

     --
     -- Make sure that package was in work-in-progress or pending before makeing it release
     -- Exclude patches, ripple builds
     --
     IF (envtab < 0)
     THEN
       -- Not found in work-in-progress or pending
       IF (ispatch IS NULL) AND (buildtype = 'M')
       THEN
         raise_application_error (-20000,
                            'This package cannot be released here.'
                           );
       END IF;
     END IF;

     -- Log
     --log_action (pvid, 'action', userid, 'Start of Make Package Release...');

     --
     -- Remove the package from the WIP or PENDING tab
     -- Do NOT remove from the release area.
     --     This will be handled later with a process that
     --     will do a 'replace' so that meta data is not lost
     --
    IF envtab = 0
    THEN
        -- WORK IN PROGRESS --
        pk_work_in_progress.remove_package (pvid, rtagid, userid);
    ELSIF envtab = 1
    THEN
        -- PENDING --
        pk_planned.remove_package (pvid, rtagid, userid);
    END IF;

    --
    --  If we are changing the pkgExt, then fully remove the base package
    --  This includes removing it from the 'release' area.
    --
    IF clone_removal = 1
    THEN
        IF clone_envtab = 0
        THEN
            -- WORK IN PROGRESS --
            pk_work_in_progress.remove_package (clonefrompvid, rtagid, userid);
        ELSIF clone_envtab = 1
        THEN
            -- PENDING --
            pk_planned.remove_package (clonefrompvid, rtagid, userid);
        ELSIF clone_envtab = 2
        THEN
            -- RELEASED --
            pk_release.remove_package (clonefrompvid, rtagid, userid);
       END IF;
    END IF;

     -- Change package state
     -- Set dlocked state to mark the package a 'Released and Locked'
     pk_package.change_state (pvid, 'Y', userid);

     -- Make sure it is valid BASE VIEW
     -- If its not specified, give it a default (7) view
     IF viewid < 1
     THEN
        IF clone_viewid >= 0
        THEN
            viewid := clone_viewid;
        ELSE
            viewid := 7;
        END IF;
     END IF;

     IF (ispatch IS NULL)
     THEN
       -- Add (Replace) package to new area
       pk_release.add_package (pvid, viewid, rtagid, userid);
     END IF;

     -- Now do post Release Actions
     pk_release.run_post_actions (pvid, rtagid);
     -- Now update the Dash_Board Table (DEPRECATED)
     pk_rmapi.update_dash_board (rtagid);

     -- The release has changed and there may now be invalid rtag_id/pv_id combinations in
     -- the DO_NOT_RIPPLE and ADVISORY_RIPPLE Tables so perform a clean-up operation upon them.
     clean_do_not_ripple(rtagid);
     clean_advisory_ripple(rtagid);

     -- Log
     --log_action (pvid, 'action', userid, 'End of Make Package Release...');
   END;


/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE make_unrelease (pvid IN NUMBER, rtagid IN NUMBER, userid IN NUMBER)
   IS
     viewid   NUMBER;
     envtab   NUMBER;
   BEGIN
     -- Get ViewId
     --ViewId := PK_RELEASE.GET_PACKAGE_VIEW ( PvId, RtagId );
     viewid := get_package_view (pvid, rtagid);
     -- Remove from current area
     envtab := pk_environment.get_package_area (pvid, rtagid);
     -- Log
     -- log_action (pvid, 'action', userid, 'Start of Make Package UnRelease...' );

     IF envtab = 2
     THEN
       -- RELEASE AREA --
       pk_release.remove_package (pvid, rtagid, userid);
     ELSIF envtab = 1
     THEN
       -- PENDING --
       pk_planned.remove_package (pvid, rtagid, userid);
     END IF;

     -- Change package state
     pk_package.change_state (pvid, 'N', userid);

     -- Make sure it is valid BASE VIEW
     IF viewid < 1
     THEN
       viewid := 7;                     -- This is default base view
     END IF;

     -- Add package to new area
     pk_work_in_progress.add_package (pvid, viewid, rtagid, userid);
     -- Now do post Release Actions
     pk_release.run_post_actions (pvid, rtagid);

     -- Log
     -- log_action (pvid, 'action', userid, 'End of Make Package UnRelease...');
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE make_pending (pvid IN NUMBER, rtagid IN NUMBER, userid IN NUMBER)
   IS
     viewid     NUMBER;
     ispatch    CHAR (1) := NULL;
     buildtype  CHAR (1) := NULL;
   BEGIN
     -- Check if package is patch
     SELECT pv.is_patch, pv.build_type
      INTO ispatch, buildtype
      FROM package_versions pv
      WHERE pv.pv_id = pvid;

     -- Get ViewId
     viewid := get_package_view (pvid, rtagid);
     --ViewId := PK_WORK_IN_PROGRESS.GET_PACKAGE_VIEW ( PvId, RtagId );

     -- Log
     --log_action (pvid, 'action', userid, 'Start of Make Package Pending...');

     IF (ispatch IS NULL)
     THEN
       -- Remove from current area
       pk_work_in_progress.remove_package (pvid, rtagid, userid);
       -- Change package state
       pk_package.change_state (pvid, 'P', userid);
       -- Add package to new area
       pk_planned.add_package (pvid, viewid, rtagid, userid);
     END IF;

     -- Log
     --log_action (pvid, 'action', userid, 'End of Make Package Pending...');
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE make_approved (pvid IN NUMBER, rtagid IN NUMBER, userid IN NUMBER, sched in VARCHAR2)
   IS
   BEGIN
     -- Log
     -- log_action (pvid, 'action', userid, 'Start of Package Pending Approval...' );
     -- Change package state
     pk_package.change_state (pvid, 'A', userid);

     -- Flag Release has changed for the purposes of building
     PK_RELEASE.SET_RELEASE_MODIFIED(rtagid);

     PK_BUILDAPI.del_daemon_inst_by_rtag_pvid(2, rtagid, pvid);
     IF sched IS NOT NULL THEN
        -- Schedule a future build of the package
        PK_BUILDAPI.insert_daemon_inst( 2, rtagid, pvid, TO_DATE( sched, 'YYYY-MM-DD HH24:MI:SS'), 0, ORA_SYSDATETIME, userid);
        log_action (pvid, 'approve_scheduled', userid, 'Scheduled build:' || sched);

     END IF;

     -- Log
     -- log_action (pvid, 'action', userid, 'End of Package Pending Approval...');
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE make_reject (pvid IN NUMBER, rtagid IN NUMBER, userid IN NUMBER)
   IS
     viewid   NUMBER;
     operation CHAR;
   BEGIN
     -- Get ViewId
     viewid := get_package_view (pvid, rtagid);
     -- ViewId := PK_PLANNED.GET_PACKAGE_VIEW ( PvId, RtagId );

     -- DEVI-45275
     -- If the package version is an official version that is to be rejected from a merge operation
     -- then find out in order to prevent it being added back to work-in-progress table . This will
     -- be denoted by the operation field in the planned table being A or S
     operation := ' ';
     SELECT
     (CASE WHEN pl.operation IS NOT NULL THEN pl.operation ELSE ' ' END) INTO operation
     FROM planned pl
     WHERE pl.PV_ID = pvid
     AND pl.RTAG_ID = rtagid;

     -- Log
     -- log_action (pvid, 'action', userid, 'Start of Reject Package...');

     -- Remove from current area
     pk_planned.remove_package (pvid, rtagid, userid);

     -- DEVI-45275 - Prevent merge candidate from being added back to work-in-progress table .
     IF operation <> 'A' AND operation <> 'S'
     THEN
     -- Change package state
     pk_package.change_state (pvid, 'R', userid);
     -- Add package to new area
     pk_work_in_progress.add_package (pvid, viewid, rtagid, userid);
     PK_BUILDAPI.del_daemon_inst_by_rtag_pvid(2, rtagid, pvid);
     ELSE
      log_action (pvid, 'action', userid, 'Rejected Package Merge');
     END IF;

     -- Log
     -- log_action (pvid, 'action', userid, 'End of Reject Package...');
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE change_package_view (
     pvid       IN   NUMBER,
     rtagid     IN   NUMBER,
     newviewid  IN   NUMBER
   )
   IS
     envtab   NUMBER;
   BEGIN
     envtab := pk_environment.get_package_area (pvid, rtagid);

     IF envtab = 0
     THEN
       -- WORK IN PROGRESS --
       pk_work_in_progress.change_package_view (pvid, rtagid, newviewid);
     ELSIF envtab = 1
     THEN
       -- PENDING --
       pk_planned.change_package_view (pvid, rtagid, newviewid);
     ELSIF envtab = 2
     THEN
       -- RELEASED --
       pk_release.change_package_view (pvid, rtagid, newviewid);
     END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE find_package (
     skeyword     IN      VARCHAR2,
     nrtagid      IN      NUMBER,
     nsearcharea  IN      NUMBER,
     recordset    OUT     typecur
   )
   IS
   BEGIN
     IF nsearcharea = 0
     THEN
       /* Search Work In Progress */
       OPEN recordset FOR
         SELECT nsearcharea AS env_area, vi.view_name, pv.dlocked,
                pkg.pkg_name, pv.pv_id, pv.pkg_version, pv.comments,
                pv.modified_stamp, usr.full_name, usr.user_email
           FROM views vi,
                work_in_progress rc,
                PACKAGES pkg,
                package_versions pv,
                users usr
          WHERE rc.view_id = vi.view_id
            AND rc.pv_id = pv.pv_id
            AND pkg.pkg_id = pv.pkg_id
            AND pv.modifier_id = usr.user_id
            AND rc.rtag_id = nrtagid
            AND UPPER (pkg.pkg_name) LIKE UPPER (skeyword)
       ORDER BY UPPER (pkg.pkg_name);
     ELSIF nsearcharea = 1
     THEN
       /* Search Pending */
       OPEN recordset FOR
         SELECT nsearcharea AS env_area, vi.view_name, pv.dlocked,
                pkg.pkg_name, pv.pv_id, pv.pkg_version, pv.comments,
                pv.modified_stamp, usr.full_name, usr.user_email
           FROM views vi,
                planned rc,
                PACKAGES pkg,
                package_versions pv,
                users usr
          WHERE rc.view_id = vi.view_id
            AND rc.pv_id = pv.pv_id
            AND pkg.pkg_id = pv.pkg_id
            AND pv.modifier_id = usr.user_id
            AND rc.rtag_id = nrtagid
            AND UPPER (pkg.pkg_name) LIKE UPPER (skeyword)
       ORDER BY UPPER (pkg.pkg_name);
     ELSIF nsearcharea = 2
     THEN
       /* Search Released */
       OPEN recordset FOR
         SELECT nsearcharea AS env_area, vi.view_name, pv.dlocked,
                pkg.pkg_name, pv.pv_id, pv.pkg_version, pv.comments,
                pv.modified_stamp, usr.full_name, usr.user_email
           FROM views vi,
                release_content rc,
                PACKAGES pkg,
                package_versions pv,
                users usr
          WHERE rc.base_view_id = vi.view_id
            AND rc.pv_id = pv.pv_id
            AND pkg.pkg_id = pv.pkg_id
            AND pv.modifier_id = usr.user_id
            AND rc.rtag_id = nrtagid
            AND UPPER (pkg.pkg_name) LIKE UPPER (skeyword)
         ORDER BY UPPER (pkg.pkg_name);
     ELSIF nsearcharea = 3
     THEN
       /* Search ALL */
       OPEN recordset FOR
         SELECT rc.env_area, vi.view_name, pv.dlocked, pkg.pkg_name,
                pv.pv_id, pv.pkg_version, pv.comments,
                pv.modified_stamp, usr.full_name, usr.user_email
           FROM views vi,
                environment_view rc,
                PACKAGES pkg,
                package_versions pv,
                users usr
          WHERE rc.view_id = vi.view_id
            AND rc.pv_id = pv.pv_id
            AND pkg.pkg_id = pv.pkg_id
            AND pv.modifier_id = usr.user_id
            AND rc.rtag_id = nrtagid
            AND UPPER (pkg.pkg_name) LIKE UPPER (skeyword)
         ORDER BY UPPER (pkg.pkg_name);
     END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE find_file (
     skeyword     IN      VARCHAR2,
     nrtagid      IN      NUMBER,
     nsearcharea  IN      NUMBER,
     npagesize    IN      NUMBER,
     recordset    OUT     typecur
   )
   IS
   BEGIN
     IF nsearcharea = 0
     THEN
       /* Search Work In Progress */
       OPEN recordset FOR
         SELECT   qry.*
            FROM (
                 /* File search on Packages */
                 SELECT art.file_name, art.file_path, pkg.pkg_name,
                        pv.pv_id, pv.pkg_version, art.crc_cksum
                   FROM work_in_progress rc,
                        PACKAGES pkg,
                        package_versions pv,
                        release_components art
                  WHERE rc.pv_id = art.pv_id
                    AND pv.pkg_id = pkg.pkg_id
                    AND rc.pv_id = pv.pv_id
                    AND rc.rtag_id = nrtagid
                    AND UPPER (art.file_name) LIKE UPPER (skeyword)
                 UNION ALL
                 /* File search on Products */
                 SELECT art.file_name, art.file_path, pkg.pkg_name,
                        pv.pv_id, pv.pkg_version, art.crc_cksum
                   FROM work_in_progress rc,
                        PACKAGES pkg,
                        package_versions pv,
                        product_components art
                  WHERE rc.pv_id = art.pv_id
                    AND pv.pkg_id = pkg.pkg_id
                    AND rc.pv_id = pv.pv_id
                    AND rc.rtag_id = nrtagid
                    AND UPPER (art.file_name) LIKE UPPER (skeyword)) qry
            WHERE ROWNUM <= npagesize
         ORDER BY UPPER (qry.pkg_name);
     ELSIF nsearcharea = 1
     THEN
       /* Search Pending */
       OPEN recordset FOR
         SELECT   qry.*
            FROM (
                 /* File search on Packages */
                 SELECT art.file_name, art.file_path, pkg.pkg_name,
                        pv.pv_id, pv.pkg_version, art.crc_cksum
                   FROM planned rc,
                        PACKAGES pkg,
                        package_versions pv,
                        release_components art
                  WHERE rc.pv_id = art.pv_id
                    AND pv.pkg_id = pkg.pkg_id
                    AND rc.pv_id = pv.pv_id
                    AND rc.rtag_id = nrtagid
                    AND UPPER (art.file_name) LIKE UPPER (skeyword)
                 UNION ALL
                 /* File search on Products */
                 SELECT art.file_name, art.file_path, pkg.pkg_name,
                        pv.pv_id, pv.pkg_version, art.crc_cksum
                   FROM planned rc,
                        PACKAGES pkg,
                        package_versions pv,
                        product_components art
                  WHERE rc.pv_id = art.pv_id
                    AND pv.pkg_id = pkg.pkg_id
                    AND rc.pv_id = pv.pv_id
                    AND rc.rtag_id = nrtagid
                    AND UPPER (art.file_name) LIKE UPPER (skeyword)) qry
            WHERE ROWNUM <= npagesize
         ORDER BY UPPER (qry.pkg_name);
     ELSIF nsearcharea = 2
     THEN
       /* Search Released */
       OPEN recordset FOR
         SELECT   qry.*
            FROM (
                 /* File search on Packages */
                 SELECT art.file_name, art.file_path, pkg.pkg_name,
                        pv.pv_id, pv.pkg_version, art.crc_cksum,
                        NULL AS patch_id
                   FROM release_content rc,
                        PACKAGES pkg,
                        package_versions pv,
                        release_components art
                  WHERE rc.pv_id = art.pv_id
                    AND pv.pkg_id = pkg.pkg_id
                    AND rc.pv_id = pv.pv_id
                    AND rc.rtag_id = nrtagid
                    AND UPPER (art.file_name) LIKE UPPER (skeyword)
                 UNION ALL
                 /* File search on Products */
                 SELECT art.file_name, art.file_path, pkg.pkg_name,
                        pv.pv_id, pv.pkg_version, art.crc_cksum,
                        NULL AS patch_id
                   FROM release_content rc,
                        PACKAGES pkg,
                        package_versions pv,
                        product_components art
                  WHERE rc.pv_id = art.pv_id
                    AND pv.pkg_id = pkg.pkg_id
                    AND rc.pv_id = pv.pv_id
                    AND rc.rtag_id = nrtagid
                    AND UPPER (art.file_name) LIKE UPPER (skeyword)
                 UNION ALL
                 /* File search on Patches */
                 SELECT art.file_name, art.file_path, pkg.pkg_name,
                        pv.pv_id, pv.pkg_version, art.crc_cksum,
                        DECODE (art.file_path,
                                NULL, pp.patch_id,
                                NULL
                                ) AS patch_id
                   FROM release_content rc,
                        PACKAGES pkg,
                        package_versions pv,
                        release_components art,
                        package_patches pp
                  WHERE pv.pv_id = pp.pv_id
                    AND pv.pkg_id = pkg.pkg_id
                    AND rc.rtag_id = nrtagid
                    AND art.pv_id = pp.patch_id
                    AND rc.pv_id = pp.pv_id
                    AND UPPER (art.file_name) LIKE UPPER (skeyword)) qry
            WHERE ROWNUM <= npagesize
         ORDER BY UPPER (qry.pkg_name);
     ELSIF nsearcharea = 3
     THEN
       /* Search ALL */
       OPEN recordset FOR
         SELECT   qry.*
            FROM (
                 /* File search on Packages */
                 SELECT art.file_name, art.file_path, pkg.pkg_name,
                        pv.pv_id, pv.pkg_version, art.crc_cksum,
                        NULL AS patch_id
                   FROM environment_view rc,
                        PACKAGES pkg,
                        package_versions pv,
                        release_components art
                  WHERE rc.pv_id = art.pv_id
                    AND pv.pkg_id = pkg.pkg_id
                    AND rc.pv_id = pv.pv_id
                    AND rc.rtag_id = nrtagid
                    AND UPPER (art.file_name) LIKE UPPER (skeyword)
                 UNION ALL
                 /* File search on Products */
                 SELECT art.file_name, art.file_path, pkg.pkg_name,
                        pv.pv_id, pv.pkg_version, art.crc_cksum,
                        NULL AS patch_id
                   FROM environment_view rc,
                        PACKAGES pkg,
                        package_versions pv,
                        product_components art
                  WHERE rc.pv_id = art.pv_id
                    AND pv.pkg_id = pkg.pkg_id
                    AND rc.pv_id = pv.pv_id
                    AND rc.rtag_id = nrtagid
                    AND UPPER (art.file_name) LIKE UPPER (skeyword)
                 UNION ALL
                 /* File search on Patches */
                 SELECT art.file_name, art.file_path, pkg.pkg_name,
                        pv.pv_id, pv.pkg_version, art.crc_cksum,
                        DECODE (art.file_path,
                                NULL, pp.patch_id,
                                NULL
                               ) AS patch_id
                   FROM release_content rc,
                        PACKAGES pkg,
                        package_versions pv,
                        release_components art,
                        package_patches pp
                  WHERE pv.pv_id = pp.pv_id
                    AND pv.pkg_id = pkg.pkg_id
                    AND rc.rtag_id = nrtagid
                    AND art.pv_id = pp.patch_id
                    AND rc.pv_id = pp.pv_id
                    AND UPPER (art.file_name) LIKE UPPER (skeyword)) qry
            WHERE ROWNUM <= npagesize
         ORDER BY UPPER (qry.pkg_name);
     END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE get_prodrelease_items (
     rtagid           IN      NUMBER,
     ntruerecordcount OUT     NUMBER,
     recordset        OUT     typecur
   )
   IS
   BEGIN
     -- Get true record count n the number of integration products
     SELECT COUNT (rc.pv_id)
      INTO ntruerecordcount
      FROM release_content rc
      WHERE rc.rtag_id = rtagid;

     OPEN recordset FOR
       SELECT vi.view_id, vi.view_name, rel.pkg_state,   --rel.pkg_state,
              rel.deprecated_state, pv.pv_id, pkg.pkg_name,
              pv.pkg_version, pv.dlocked, pv.pv_description
         FROM release_content rel,
              PACKAGES pkg,
              package_versions pv,
              views vi
        WHERE pv.pkg_id = pkg.pkg_id
          AND rel.pv_id = pv.pv_id
          AND rel.base_view_id = vi.view_id
          AND pv.is_deployable = 'Y'
          AND rtag_id = rtagid
          AND pv.pv_id NOT IN (SELECT DISTINCT prod_id
                                 FROM deployment_manager.os_contents)
          AND rel.product_state IS NULL
     ORDER BY UPPER (vi.view_name), UPPER (pkg.pkg_name);
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE get_integration_items (
     rtagid           IN      NUMBER,
     ntruerecordcount OUT     NUMBER,
     recordset        OUT     typecur
   )
   IS
   BEGIN
     -- Get true record count n the number of integration products
     SELECT COUNT (rc.pv_id)
      INTO ntruerecordcount
      FROM release_content rc
      WHERE rc.rtag_id = rtagid AND rc.product_state = 1;

     OPEN recordset FOR
       SELECT vi.view_id, vi.view_name, rel.pkg_state,
              rel.deprecated_state, pv.pv_id, pkg.pkg_name,
              pv.pkg_version, pv.dlocked, pv.pv_description
         FROM release_content rel,
              PACKAGES pkg,
              package_versions pv,
              views vi
        WHERE pv.pkg_id = pkg.pkg_id
          AND rel.pv_id = pv.pv_id
          AND rel.base_view_id = vi.view_id
          AND pv.is_deployable = 'Y'
          AND rtag_id = rtagid
          AND rel.product_state IN (1, 5)
     ORDER BY UPPER (vi.view_name), UPPER (pkg.pkg_name);
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE get_test_items (
     rtagid           IN      NUMBER,
     ntruerecordcount OUT     NUMBER,
     recordset        OUT     typecur
   )
   IS
   BEGIN
     -- Get true record count n the number of test products
     SELECT COUNT (rc.pv_id)
      INTO ntruerecordcount
      FROM release_content rc
      WHERE rc.rtag_id = rtagid AND rc.product_state = 2;

     OPEN recordset FOR
       SELECT vi.view_id, vi.view_name, rel.pkg_state,
              rel.deprecated_state, pv.pv_id, pkg.pkg_name,
              pv.pkg_version, pv.dlocked, pv.pv_description
         FROM release_content rel,
              PACKAGES pkg,
              package_versions pv,
              views vi
        WHERE pv.pkg_id = pkg.pkg_id
          AND rel.pv_id = pv.pv_id
          AND rel.base_view_id = vi.view_id
          AND pv.is_deployable = 'Y'
          AND rtag_id = rtagid
          AND rel.product_state = 2
     ORDER BY UPPER (vi.view_name), UPPER (pkg.pkg_name);
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE get_deploy_items (
     rtagid           IN      NUMBER,
     ntruerecordcount OUT     NUMBER,
     recordset        OUT     typecur
   )
   IS
   BEGIN
     -- Get true record count n the number of deploy products
     SELECT COUNT (rc.pv_id)
      INTO ntruerecordcount
      FROM release_content rc
      WHERE rc.rtag_id = rtagid AND rc.product_state = 3;

     OPEN recordset FOR
       SELECT vi.view_id, vi.view_name, rel.pkg_state,
              rel.deprecated_state, pv.pv_id, pkg.pkg_name,
              pv.pkg_version, pv.dlocked, pv.pv_description
         FROM release_content rel,
              PACKAGES pkg,
              package_versions pv,
              views vi
        WHERE pv.pkg_id = pkg.pkg_id
          AND rel.pv_id = pv.pv_id
          AND rel.base_view_id = vi.view_id
          AND pv.is_deployable = 'Y'
          AND rtag_id = rtagid
          AND rel.product_state IN (3, 5)
          AND pv.pv_id NOT IN (SELECT DISTINCT prod_id
                                 FROM deployment_manager.os_contents)
     ORDER BY UPPER (vi.view_name), UPPER (pkg.pkg_name);
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE get_reject_items (
     rtagid           IN      NUMBER,
     ntruerecordcount OUT     NUMBER,
     recordset        OUT     typecur
   )
   IS
   BEGIN
     -- Get true record count n the number of reject products
     SELECT COUNT (rc.pv_id)
       INTO ntruerecordcount
       FROM release_content rc
      WHERE rc.rtag_id = rtagid AND rc.product_state = 4;

     OPEN recordset FOR
       SELECT vi.view_id, vi.view_name, rel.pkg_state,
              rel.deprecated_state, pv.pv_id, pkg.pkg_name,
              pv.pkg_version, pv.dlocked, pv.pv_description
         FROM release_content rel,
              PACKAGES pkg,
              package_versions pv,
              views vi
        WHERE pv.pkg_id = pkg.pkg_id
          AND rel.pv_id = pv.pv_id
          AND rel.base_view_id = vi.view_id
          AND pv.is_deployable = 'Y'
          AND rtag_id = rtagid
          AND rel.product_state = 4
     ORDER BY UPPER (vi.view_name), UPPER (pkg.pkg_name);
   END;
/*-------------------------------------------------------------------------------------------------------*/
   -- DEVI-45275 - this procedure performs the merge of an existing package version in the planned table
   -- to the release_content table.

  PROCEDURE approve_merge (
   PvId    IN NUMBER,
   RtagId  IN NUMBER,
   UserId  IN NUMBER
  )
  IS
   viewid        NUMBER;
   envtab        NUMBER;
   oper         CHAR;
  BEGIN
      -- Get ViewId
     viewid := get_package_view (pvid, rtagid);

     -- Get the view tab
     envtab := pk_environment.get_package_area (pvid, rtagid);

     -- Make sure that package was in pending before merging it to released
     IF (envtab <> 1)
     THEN
       -- Not found in pending
       raise_application_error (-20000,
                          'This package cannot be released here.'
                         );
     END IF;

     -- Log
     --log_action (pvid, 'action', userid, 'Start of Package Merge...');

     -- Get the planned operation type A=Add, S=Subtract
     SELECT ev.operation INTO oper
       FROM environment_view ev
      WHERE ev.rtag_id = RtagId
        AND ev.pv_id = PvId
        AND (ev.operation = 'A' OR ev.operation = 'S');

     -- Remove from Pending
     pk_planned.remove_package (PvId, RtagId, UserId);

     -- Either add to the release, or remove from the release as the operation commands
     IF oper = 'A'
     THEN
       pk_release.add_package(PvId, viewId, RtagId, UserId);

     ELSIF oper = 'S'
     THEN
       pk_release.remove_package(PvId, RtagId, UserId);

       -- Delete old package's pegging info
       DELETE FROM PEGGED_VERSIONS pegv WHERE pegv.RTAG_ID = RtagId AND pegv.PV_ID = PvId;

       -- Delete old package's advisory ripple info
       DELETE FROM ADVISORY_RIPPLE avr WHERE avr.RTAG_ID = RtagId AND avr.PV_ID = PvId;
     END IF;

     touch_release(RtagId);

     -- Log
     --log_action (pvid, 'action', userid, 'End of Package Merge...');
  END;
/*-------------------------------------------------------------------------------------------------------*/
END pk_environment;

/
--------------------------------------------------------
--  DDL for Package Body PK_LICENCING
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE BODY "RELEASE_MANAGER"."PK_LICENCING" IS

/*
------------------------------
||  Last Modified:  G.Huddy
||  Modified Date:  19/Aug/2008
||  Body Version:   1.0
------------------------------
*/

   PROCEDURE ADD_LICENCE ( PvId IN NUMBER, licenceId IN NUMBER, UserId IN NUMBER ) IS
   BEGIN
      IF IS_LICENCED(PvId, licenceId) = 0 THEN
         -- Add entry to licencing table
         INSERT INTO licencing (pv_id, licence)
         VALUES (PvId, licenceId);

         -- log action
         -- TODO
      END IF;

   END;

/*-------------------------------------------------------------------------------------------------------*/

   PROCEDURE REMOVE_LICENCE ( PvId IN NUMBER, licenceId IN NUMBER, UserId IN NUMBER ) IS
   BEGIN
      IF NOT IS_LICENCED(PvId, licenceId) = 0 THEN
         -- Delete entry from licencing table
         DELETE FROM licencing
         WHERE pv_id = PvId
         AND licence = licenceId;

         -- log action
         -- TODO
      END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/

   PROCEDURE CLONE_LICENCING( fromPvId IN NUMBER, toPvId IN NUMBER, UserId IN NUMBER ) IS

      CURSOR licencing_cur
      IS
         SELECT *
         FROM licencing
         WHERE pv_id = fromPvId;

      licencing_rec licencing_cur%ROWTYPE;

   BEGIN
      -- For each licence association that the Last PV_ID had, create a similar
      -- arrangement for the new PV_ID
      -- NOTE that any additional licencing associations the new PV_ID has that the old one
      -- does not have, are retained. The assumption is that the user has made those and so we do not
      -- have any right to destroy them without asking them.
      OPEN licencing_cur;

      FETCH licencing_cur
      INTO licencing_rec;

      WHILE licencing_cur%FOUND
      LOOP
         ADD_LICENCE ( toPvId, licencing_rec.licence, UserId );

         FETCH licencing_cur
         INTO licencing_rec;
      END LOOP;
   END;

/*-------------------------------------------------------------------------------------------------------*/

   FUNCTION IS_LICENCED( PvId IN NUMBER, licenceId IN NUMBER) RETURN NUMBER IS
      found NUMBER;
   BEGIN

      SELECT COUNT(*) INTO found
      FROM licencing
      WHERE pv_id = PvId
      AND licence = LicenceId;

      RETURN found;
   END;

/*-------------------------------------------------------------------------------------------------------*/

   PROCEDURE REMOVE_ALL_LICENCING( PvId IN NUMBER, UserId IN NUMBER ) IS

      CURSOR licencing_cur
      IS
         SELECT *
         FROM licencing
         WHERE pv_id = PvId;

      licencing_rec licencing_cur%ROWTYPE;
   BEGIN
      -- For each licence association that the PV_ID had, remove it
      OPEN licencing_cur;

      FETCH licencing_cur
      INTO licencing_rec;

      WHILE licencing_cur%FOUND
      LOOP
         REMOVE_LICENCE ( PvId, licencing_rec.licence, UserId );

         FETCH licencing_cur
         INTO licencing_rec;
      END LOOP;
   END;

/*-------------------------------------------------------------------------------------------------------*/
END PK_LICENCING;

/
--------------------------------------------------------
--  DDL for Package Body PK_PACKAGE
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE BODY "RELEASE_MANAGER"."PK_PACKAGE" 
IS
   /*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE new_version (
      nlastpvid                   IN       NUMBER,
      snewpkgversion              IN       VARCHAR2 DEFAULT NULL,
      cbuildtype                  IN       CHAR,
      cchangetype                 IN       CHAR,
      nsettopvid                  IN       NUMBER DEFAULT NULL,
      nrtagid                     IN       NUMBER,
      nuserid                     IN       NUMBER,
      enumissues_state_imported   IN       NUMBER,
      returnpvid                  OUT      NUMBER
   )
   IS
      origpkg_id                  package_versions.pkg_id%TYPE;
      origdlocked                 package_versions.dlocked%TYPE;
      ssv_mm                      package_versions.v_mm%TYPE;
      ssv_nmm                     package_versions.v_nmm%TYPE;
      ssv_ext                     package_versions.v_ext%TYPE;
      spackageversion             VARCHAR2 (4000);
      nissuestypes                NUMBER;
      nviewid                     NUMBER;
      reccount                    NUMBER;
      isreleased                  package_versions.dlocked%TYPE := 'N';
      slabel                      VARCHAR2 (4000)               := NULL;
      uchangetype                 CHAR := cchangetype;

      CURSOR package_versions_cur
      IS
         SELECT pv.pv_id, pv.is_patch, pv.dlocked
           FROM package_versions pv
          WHERE pv.pkg_version = snewpkgversion
            AND pv.pkg_id IN (SELECT DISTINCT origpv.pkg_id
                                         FROM package_versions origpv
                                        WHERE origpv.pv_id = nlastpvid);

      package_versions_rec package_versions_cur%ROWTYPE;

      CURSOR clone_package_versions_cur
      IS
         SELECT DISTINCT pkg_id, dlocked
                    FROM package_versions
                   WHERE pv_id = nlastpvid;

      clone_package_versions_rec clone_package_versions_cur%ROWTYPE;
   BEGIN
      spackageversion := snewpkgversion;

      IF nsettopvid IS NULL
      THEN
         -- SetToPv_id is not supplied, hence proceed.

         /* ---------------------------------------------------- */
         /* Find id package_version exists                       */
         /* ---------------------------------------------------- */
         OPEN package_versions_cur;

         FETCH package_versions_cur
          INTO package_versions_rec;

         IF package_versions_cur%NOTFOUND
         THEN
            ---  Create brand new package ---
            SELECT seq_pv_id.NEXTVAL
              INTO returnpvid
              FROM DUAL;

            -- Split Version to get extention + other
            split_version (spackageversion, ssv_mm, ssv_nmm, ssv_ext);

            -- Get previous package to clone from
            OPEN clone_package_versions_cur;

            FETCH clone_package_versions_cur
             INTO clone_package_versions_rec;

            origpkg_id := clone_package_versions_rec.pkg_id;
            origdlocked := clone_package_versions_rec.dlocked;

            CLOSE clone_package_versions_cur;

            -- Automated built config
            IF ( cbuildtype = 'M' ) THEN
              uchangetype := 'F';
            END IF;

            -- Automated version numbering
            -- Make sure that version is still unique
            IF (uchangetype != 'F') THEN
              spackageversion := '(' || returnpvid || ')' || ssv_ext;
            END IF;


            -- Clone Package Version Details --
            INSERT INTO package_versions(pv_id, pkg_id, pkg_version, dlocked, created_stamp,
                                         creator_id, modified_stamp, modifier_id, v_mm, v_nmm,
                                         v_ext, src_path, pv_description, pv_overview,
                                         last_pv_id, owner_id, is_deployable,
                                         is_build_env_required, build_type, change_type,
                                         bs_id, is_autobuildable, ripple_field, build_time)
                 SELECT returnpvid AS pv_id, origpkg_id AS pkg_id,
                        spackageversion AS pkg_version, 'N' AS dlocked,
                        ora_sysdatetime AS created_stamp, nuserid AS creator_id,
                        ora_sysdatetime AS modified_stamp,
                        nuserid AS modifier_id, ssv_mm AS v_mm,
                        ssv_nmm AS v_nmm, ssv_ext AS v_ext, pv.src_path,
                        pv.pv_description, pv.pv_overview,
                        nlastpvid AS last_pv_id, pv.owner_id, pv.is_deployable,
                        pv.is_build_env_required, cbuildtype, uchangetype,
                        pv.bs_id, pv.is_autobuildable, pv.ripple_field, pv.build_time
                   FROM package_versions pv
                  WHERE pv.pv_id = nlastpvid;

            -- Set Issues Type for cloning ---
            IF origdlocked = 'Y'
            THEN
               nissuestypes := enumissues_state_imported;
            ELSE
               nissuestypes := NULL;
            END IF;

            basic_clone (nlastpvid,
                         returnpvid,
                         nrtagid,
                         nuserid,
                         origpkg_id,
                         nissuestypes
                        );

            -- Update Label for versioning purposes
            slabel := get_automated_label (returnpvid);
            UPDATE package_versions pv
            SET pv.pkg_label = slabel
            WHERE pv.pv_id = returnpvid;

         ELSE
            --- Package already exists, hence reuse ---
            returnpvid := package_versions_rec.pv_id;
            isreleased := package_versions_rec.dlocked;
         END IF;

         CLOSE package_versions_cur;
      ELSE
         returnpvid := nsettopvid;
      END IF;
   END new_version;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE change_state (
      pvid       IN   NUMBER,
      newstate   IN   package_versions.dlocked%TYPE,
      userid     IN   NUMBER
   )
   IS
   BEGIN
      -- Set package in Released mode
      UPDATE package_versions pv
         SET pv.dlocked = newstate,
             pv.modified_stamp = ora_sysdatetime,
             pv.modifier_id = userid
       WHERE pv.pv_id = pvid;

      -- Log action --
      IF newstate = 'Y'
      THEN
         -- RELEASED --
         log_action (pvid,
                     'makeofficial',
                     userid,
                     'Package state change to: Released'
                    );
      ELSIF newstate = 'N'
      THEN
         -- UNLOCKED --
         log_action (pvid,
                     'makeunofficial',
                     userid,
                     'Package state change to: Ulocked'
                    );
      ELSIF newstate = 'P'
      THEN
         -- PENDING APPROVAL --
         log_action (pvid,
                     'add_to_planned',
                     userid,
                     'Package state change to: Pending Approval'
                    );
      ELSIF newstate = 'R'
      THEN
         -- REJECTED --
         log_action (pvid,
                     'reject_package',
                     userid,
                     'Package state change to: Rejected'
                    );
      ELSIF newstate = 'A'
      THEN
         -- APPROVED --
         log_action (pvid,
                     'approve_package',
                     userid,
                     'Package state change to: Approved'
                    );
      END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/
-- This function has been deprecated and can be deleted
-- Replaced with destroy_package_extended
   PROCEDURE destroy_package (
      pvid               IN       NUMBER,
      overridewarnings   IN       CHAR DEFAULT 'N',
      problemstring      OUT      VARCHAR2
   )
   IS
      LOCKED     CHAR;
      pkgid      NUMBER;
      ROWCOUNT   NUMBER;
      lastPvid   NUMBER;
   BEGIN
      /*
      || This will destroy all package details from database.
      || It will only be used to remove unwanted work in progress packages,
      || or mistaken versions
      */

      /*--------------- Business Rules Here -------------------*/
      problemstring := NULL;

      IF overridewarnings = 'N'
      THEN
         -- Package must not be official
         SELECT pv.dlocked
           INTO LOCKED
           FROM package_versions pv
          WHERE pv.pv_id = pvid;

         IF LOCKED = 'Y'
         THEN
            problemstring :=
                  problemstring
               || '- Package is locked and released.'
               ||PK_PACKAGE.crlf;
         END IF;

         -- Cannot remove if used in BOMs
         SELECT COUNT (osc.prod_id)
           INTO ROWCOUNT
           FROM deployment_manager.os_contents osc
          WHERE osc.prod_id = pvid;

         IF ROWCOUNT > 0
         THEN
            problemstring :=
                  problemstring
               || '- Package is part of Bill-Of-Material (BOM) in Deployment Manager.'
               ||PK_PACKAGE.crlf;
         END IF;
         
         -- Cannot remove if used in an SDK
         SELECT COUNT (sc.pv_id)
           INTO ROWCOUNT
           FROM sdk_content sc
          WHERE sc.pv_id = pvid;

         IF ROWCOUNT > 0
         THEN
            problemstring :=
                  problemstring
               || '- Package is part of an SDK.'
               ||PK_PACKAGE.crlf;
         END IF;

         -- Cannot remove if Referenced as build dependency
         SELECT COUNT (dep.pv_id)
           INTO ROWCOUNT
           FROM package_dependencies dep
          WHERE dep.dpv_id = pvid;

         IF ROWCOUNT > 0
         THEN
            problemstring :=
                  problemstring
               || '- Package is referenced by other package as build dependency.'
               ||PK_PACKAGE.crlf;
         END IF;

         -- Cannot remove if Referenced as runtime dependency
         SELECT COUNT (rd.pv_id)
           INTO ROWCOUNT
           FROM runtime_dependencies rd
          WHERE rd.rtd_id = pvid;

         IF ROWCOUNT > 0
         THEN
            problemstring :=
                  problemstring
               || '- Package is referenced by other package as runtime dependency.'
               ||PK_PACKAGE.crlf;
         END IF;

         -- Cannot remove if Referenced as patch
         SELECT COUNT (pp.pv_id)
           INTO ROWCOUNT
           FROM package_patches pp
          WHERE pp.patch_id = pvid;

         IF ROWCOUNT > 0
         THEN
            problemstring :=
                  problemstring
               || '- Package is used as patch by other package.'
               ||PK_PACKAGE.crlf;
         END IF;
      
         -- Cannot remove if a Daemon Instruction
         SELECT COUNT (di.pv_id)
           INTO ROWCOUNT
           FROM DAEMON_INSTRUCTIONS di
          WHERE di.pv_id = pvid;

         IF ROWCOUNT > 0
         THEN
            problemstring :=
                  problemstring
               || '- Package is in use for a Daemon Instruction.'
               ||PK_PACKAGE.crlf;
         END IF;
         
         
      END IF;      

/*-------------------------------------------------------*/
      IF (problemstring IS NULL)
      THEN
         --- Remove From Work in Progress
         DELETE FROM work_in_progress wip
               WHERE wip.pv_id = pvid;

         --- Remove From Pending
         DELETE FROM planned pl
               WHERE pl.pv_id = pvid;

         --- Remove From Released area
         DELETE FROM release_content rc
               WHERE rc.pv_id = pvid;

         ---Remove From Package Processes
         DELETE FROM package_processes pp
               WHERE pp.pv_id = pvid;

         --- Remove Dependencies
         DELETE FROM package_dependencies dep
               WHERE dep.pv_id = pvid;

         DELETE FROM package_dependencies dep
               WHERE dep.dpv_id = pvid;

         --- Remove Runtime dependencies
         DELETE FROM runtime_dependencies rtd
               WHERE rtd.pv_id = pvid;

         DELETE FROM runtime_dependencies rtd
               WHERE rtd.rtd_id = pvid;

         --- Remove components
         DELETE FROM product_components pc
               WHERE pc.pv_id = pvid;

         DELETE FROM release_components rc
               WHERE rc.pv_id = pvid;

         --- Remove From Notification History
         DELETE FROM notification_history nh
               WHERE nh.pv_id = pvid;

         --- Remove From Ignore Warnings
         DELETE FROM ignore_warnings iw
               WHERE iw.pv_id = pvid;

         --- Remove From Additional Notes
         DELETE FROM additional_notes an
               WHERE an.pv_id = pvid;

         --- Remove From CQ Issues
         DELETE FROM cq_issues cq
               WHERE cq.pv_id = pvid;

         --- Remove from Package Patches
         DELETE FROM package_patches pp
               WHERE pp.pv_id = pvid;

         DELETE FROM package_patches pp
               WHERE pp.patch_id = pvid;

         --- Remove From Package Documents
         DELETE FROM package_documents pd
               WHERE pd.pv_id = pvid;

         --- Remove from Code Review
         DELETE FROM code_reviews cr
               WHERE cr.pv_id = pvid;

         --- Remove from Code Review URL
         DELETE FROM code_review_url cru
               WHERE cru.pv_id = pvid;

         --- Remove from Unit Tests
         DELETE FROM unit_tests ut
               WHERE ut.pv_id = pvid;

         --- Remove from Package BuildEnv
         DELETE FROM package_build_env pbe
               WHERE pbe.pv_id = pvid;

         --- Remove from Package Build Info
         DELETE FROM package_build_info pbi
               WHERE pbi.pv_id = pvid;
               
        --- Remove from Build Plan
         DELETE FROM BUILD_PLAN bp
               WHERE bp.pv_id = pvid;
               
         --- Remove from Build Instances
         DELETE FROM BUILD_INSTANCES bi
               WHERE bi.pv_id = pvid;

         --- Remove from Build Order
         DELETE FROM build_order bo
               WHERE bo.pv_id = pvid;

         --- Remove from Licencing
         PK_LICENCING.REMOVE_ALL_LICENCING( pvid, 0 );

         --- Remove from Note Manager
         DELETE FROM note_manager nm
               WHERE nm.nid = pvid;

         --- Remove from Action log
         DELETE FROM action_log al
               WHERE al.pv_id = pvid;

         --- Remove from Do Not Ripple
         DELETE FROM DO_NOT_RIPPLE dnr
               WHERE dnr.PV_ID = pvid;
               
        --- Remove from SDK
        DELETE FROM SDK_CONTENT sc
            WHERE sc.PV_ID = pvid;
            
        -- Remove from daemon Instruction
        DELETE FROM DAEMON_INSTRUCTIONS di
          WHERE di.PV_ID = pvid;

         --- Remove from Advisory Ripple
         DELETE FROM ADVISORY_RIPPLE ar
               WHERE ar.PV_ID = pvid;

         --- Remove from Jira Issues
         DELETE FROM JIRA_ISSUES jira
               WHERE jira.PV_ID = pvid;

         --- Remove from Package Metrics
         DELETE FROM package_metrics pm
              WHERE pm.pv_id = pvid;

         -- Delete from Pegged Versions
         DELETE FROM pegged_versions pegv
              WHERE pegv.pv_id = pvid;

         --- Finally Remove From Package Versions
         --- Get Package name
         SELECT pv.pkg_id, pv.LAST_PV_ID
           INTO pkgid, lastPvid
           FROM package_versions pv
          WHERE pv.pv_id = pvid;
          
          --- Relink packages last_pv_id
          IF lastPvid is NOT NULL AND pvid !=  lastPvid THEN
            UPDATE package_versions pv
               SET pv.LAST_PV_ID = lastPvid
             WHERE pv.LAST_PV_ID = pvid;
          END IF;
          
         --- Delete the version
         DELETE FROM package_versions pv
               WHERE pv.pv_id = pvid;

         --- Remove package name if not used any more
         SELECT COUNT (pv.pv_id)
           INTO ROWCOUNT
           FROM package_versions pv
          WHERE pv.pkg_id = pkgid;

         IF ROWCOUNT < 1
         THEN
            DELETE FROM PACKAGES pkg
                  WHERE pkg.pkg_id = pkgid;
         END IF;
      END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/
    PROCEDURE destroy_package_extended (
      pvid               IN       NUMBER,
      rtagid             IN       NUMBER,
      overridewarnings   IN       NUMBER DEFAULT 0,
      RESULTS            OUT      SYS_REFCURSOR
      -- pvid - The pvid of the package to delete

      -- rtagid - Package is allowed to exist in this release

      -- overridewarnings
      --    0   - Do not delete, just test
      --    1   - Delete package if there are only advisory warnings
      --    2   - Delete package even if there are FoolHardy warnings

      -- Results [OUTPUT]
      --    Message Text, Error Level
      --    Where error Level is
      --        'A' - Advisory.
      --        'F' - Foolhardy. Will damage releases, SBOMs and other packages
   )
   IS
      LOCKED     CHAR;
      pkgid      NUMBER;
      ROWCOUNT   NUMBER;
      lastPvid   NUMBER;

      vartbl RELMGR_PKG_DESTROY_ERR_TAB_T := RELMGR_PKG_DESTROY_ERR_TAB_T();
      ii NUMBER;

      -- Add message to table that will be returned
      PROCEDURE ADD_MESSAGE( p1 IN VARCHAR2, p2 IN CHAR)
      IS
      BEGIN
        ii := ii + 1;
        vartbl.extend;
        vartbl(ii) := RELMGR_PKG_DESTROY_ERR_T(p1,UPPER(p2));
      END; 

   BEGIN
      /*
      || This will destroy all package details from database.
      || It will only be used to remove unwanted work in progress packages,
      || or mistaken versions
      */

      /*--------------- Business Rules Here -------------------*/
      ii := 0;

      IF overridewarnings < 1
      THEN
         -- Package must not be official
         SELECT pv.dlocked
           INTO LOCKED
           FROM package_versions pv
          WHERE pv.pv_id = pvid;

         IF LOCKED = 'Y'
         THEN
            ADD_MESSAGE ('Package Version is locked and released.', 'A');
         END IF;

         -- Cannot remove if a WIP
         SELECT COUNT (pv_id)
           INTO ROWCOUNT
           FROM work_in_progress wip
          WHERE wip.pv_id = pvid AND wip.RTAG_ID != rtagid;

         IF ROWCOUNT > 0
         THEN
            ADD_MESSAGE ('Version is in use as a WIP.', 'A');
         END IF;

         -- Cannot remove if a PENDING
         SELECT COUNT (pv_id)
           INTO ROWCOUNT
           FROM planned pl
          WHERE pl.pv_id = pvid AND pl.RTAG_ID != rtagid;

         IF ROWCOUNT > 0
         THEN
            ADD_MESSAGE ('Version is Pending in a release.', 'A');
         END IF;

         -- Cannot remove if in a Release
         SELECT COUNT (pv_id)
           INTO ROWCOUNT
           FROM release_content rc
          WHERE pv_id = pvid AND rc.RTAG_ID != rtagid;

         IF ROWCOUNT > 1
         THEN
            ADD_MESSAGE ('Version is a part of another Releases.', 'A');
         END IF;
         

         -- Cannot remove if a Daemon Instruction
         SELECT COUNT (di.pv_id)
           INTO ROWCOUNT
           FROM DAEMON_INSTRUCTIONS di
          WHERE di.pv_id = pvid;

         IF ROWCOUNT > 0
         THEN
            ADD_MESSAGE ('Version has outstanding Daemon Instruction.', 'A');
         END IF;

      END IF;

      IF overridewarnings < 2
      THEN
         -- Cannot remove if used in BOMs
         SELECT COUNT (osc.prod_id)
           INTO ROWCOUNT
           FROM deployment_manager.os_contents osc
          WHERE osc.prod_id = pvid;

         IF ROWCOUNT > 0
         THEN
            ADD_MESSAGE ('Version is part of Bill-Of-Material (BOM) in Deployment Manager.', 'F');
         END IF;

         -- Cannot remove if used in BOMs - Base Env
         SELECT COUNT (bec.prod_id)
           INTO ROWCOUNT
           FROM deployment_manager.base_env_contents bec
          WHERE bec.prod_id = pvid;

         IF ROWCOUNT > 0
         THEN
            ADD_MESSAGE ('Version is part of Base Environment in Deployment Manager.', 'F');
         END IF;
         
         -- Cannot remove if used in an SDK
         SELECT COUNT (sc.pv_id)
           INTO ROWCOUNT
           FROM sdk_content sc
          WHERE sc.pv_id = pvid;

         IF ROWCOUNT > 0
         THEN
            ADD_MESSAGE ('Version is part of an SDK', 'F');
         END IF;

         -- Cannot remove if Referenced as build dependency
         SELECT COUNT (dep.pv_id)
           INTO ROWCOUNT
           FROM package_dependencies dep
          WHERE dep.dpv_id = pvid;

         IF ROWCOUNT > 0
         THEN
            ADD_MESSAGE ('Version is referenced by a package as build dependency.', 'F');
         END IF;

         -- Cannot remove if Referenced as runtime dependency
         SELECT COUNT (rd.pv_id)
           INTO ROWCOUNT
           FROM runtime_dependencies rd
          WHERE rd.rtd_id = pvid;

         IF ROWCOUNT > 0
         THEN
            ADD_MESSAGE ('Version is referenced by other package as a runtime dependency.', 'F');
         END IF;

         -- Cannot remove if Referenced as patch
         SELECT COUNT (pp.pv_id)
           INTO ROWCOUNT
           FROM package_patches pp
          WHERE pp.patch_id = pvid;

         IF ROWCOUNT > 0
         THEN
            ADD_MESSAGE ('Version is used as a patch by other package.', 'F');
         END IF;
      
      END IF;

/*-------------------------------------------------------*/
      IF (ii = 0 AND overridewarnings > 0)
      THEN
         --- Remove From Work in Progress
         DELETE FROM work_in_progress wip
               WHERE wip.pv_id = pvid;

         --- Remove From Pending
         DELETE FROM planned pl
               WHERE pl.pv_id = pvid;

         --- Remove From Released area
         DELETE FROM release_content rc
               WHERE rc.pv_id = pvid;

         ---Remove From Package Processes
         DELETE FROM package_processes pp
               WHERE pp.pv_id = pvid;

         --- Remove Dependencies
         DELETE FROM package_dependencies dep
               WHERE dep.pv_id = pvid;

         DELETE FROM package_dependencies dep
               WHERE dep.dpv_id = pvid;

         --- Remove Runtime dependencies
         DELETE FROM runtime_dependencies rtd
               WHERE rtd.pv_id = pvid;

         DELETE FROM runtime_dependencies rtd
               WHERE rtd.rtd_id = pvid;

         --- Remove components
         DELETE FROM product_components pc
               WHERE pc.pv_id = pvid;

         DELETE FROM release_components rc
               WHERE rc.pv_id = pvid;

         --- Remove From Notification History
         DELETE FROM notification_history nh
               WHERE nh.pv_id = pvid;

         --- Remove From Ignore Warnings
         DELETE FROM ignore_warnings iw
               WHERE iw.pv_id = pvid;

         --- Remove From Additional Notes
         DELETE FROM additional_notes an
               WHERE an.pv_id = pvid;

         --- Remove From CQ Issues
         DELETE FROM cq_issues cq
               WHERE cq.pv_id = pvid;

         --- Remove from Package Patches
         DELETE FROM package_patches pp
               WHERE pp.pv_id = pvid;

         DELETE FROM package_patches pp
               WHERE pp.patch_id = pvid;

         --- Remove From Package Documents
         DELETE FROM package_documents pd
               WHERE pd.pv_id = pvid;

         --- Remove from Code Review
         DELETE FROM code_reviews cr
               WHERE cr.pv_id = pvid;

         --- Remove from Code Review URL
         DELETE FROM code_review_url cru
               WHERE cru.pv_id = pvid;

         --- Remove from Unit Tests
         DELETE FROM unit_tests ut
               WHERE ut.pv_id = pvid;

         --- Remove from Package BuildEnv
         DELETE FROM package_build_env pbe
               WHERE pbe.pv_id = pvid;

         --- Remove from Package Build Info
         DELETE FROM package_build_info pbi
               WHERE pbi.pv_id = pvid;
               
        --- Remove from Build Plan
         DELETE FROM BUILD_PLAN bp
               WHERE bp.pv_id = pvid;
               
         --- Remove from Build Instances
         DELETE FROM BUILD_INSTANCES bi
               WHERE bi.pv_id = pvid;

         --- Remove from Build Order
         DELETE FROM build_order bo
               WHERE bo.pv_id = pvid;

         --- Remove from Licencing
         PK_LICENCING.REMOVE_ALL_LICENCING( pvid, 0 );

         --- Remove from Note Manager
         DELETE FROM note_manager nm
               WHERE nm.nid = pvid;

         --- Remove from Action log
         DELETE FROM action_log al
               WHERE al.pv_id = pvid;

         --- Remove from Do Not Ripple
         DELETE FROM DO_NOT_RIPPLE dnr
               WHERE dnr.PV_ID = pvid;
               
        --- Remove from SDK
        DELETE FROM SDK_CONTENT sc
            WHERE sc.PV_ID = pvid;
            
        -- Remove from daemon Instruction
        DELETE FROM DAEMON_INSTRUCTIONS di
          WHERE di.PV_ID = pvid;

         --- Remove from Advisory Ripple
         DELETE FROM ADVISORY_RIPPLE ar
               WHERE ar.PV_ID = pvid;

         --- Remove from Jira Issues
         DELETE FROM JIRA_ISSUES jira
               WHERE jira.PV_ID = pvid;

         --- Remove from Package Metrics
         DELETE FROM package_metrics pm
              WHERE pm.pv_id = pvid;

         -- Delete from Pegged Versions
         DELETE FROM pegged_versions pegv
              WHERE pegv.pv_id = pvid;

         --- Finally Remove From Package Versions
         --- Get Package name
         SELECT pv.pkg_id, pv.LAST_PV_ID
           INTO pkgid, lastPvid
           FROM package_versions pv
          WHERE pv.pv_id = pvid;
          
          --- Relink packages last_pv_id
          IF lastPvid is NOT NULL AND pvid !=  lastPvid THEN
            UPDATE package_versions pv
               SET pv.LAST_PV_ID = lastPvid
             WHERE pv.LAST_PV_ID = pvid;
          END IF;
          
         --- Delete the version
         DELETE FROM package_versions pv
               WHERE pv.pv_id = pvid;

         --- Remove package name if not used any more
         SELECT COUNT (pv.pv_id)
           INTO ROWCOUNT
           FROM package_versions pv
          WHERE pv.pkg_id = pkgid;

         IF ROWCOUNT < 1
         THEN
            DELETE FROM PACKAGES pkg
                  WHERE pkg.pkg_id = pkgid;
         END IF;
      END IF;

      --- Return table of reasons the package shouldn't be destroyed
       open RESULTS for select * from table(vartbl);

   END;
      
/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE new_patch (
      snewpatchversion   IN       package_versions.pkg_version%TYPE,
      nparentpvid        IN       NUMBER,
      spatchidlist       IN       VARCHAR2,
      nuserid            IN       NUMBER,
      returnpatchid      OUT      NUMBER
   )
   IS
      patchpv_id           NUMBER;
      parpkg_id            NUMBER;
      lastinstallorder     NUMBER;
      ispatchdlocked       package_versions.dlocked%TYPE;
      ssv_mm               package_versions.v_mm%TYPE;
      ssv_nmm              package_versions.v_nmm%TYPE;
      ssv_ext              package_versions.v_ext%TYPE;
      opatchdepcollector   relmgr_number_tab_t  := relmgr_number_tab_t ();

      CURSOR parent_cur
      IS
         SELECT pv.*, pkg.pkg_name
           FROM package_versions pv, PACKAGES pkg
          WHERE pv.pv_id = nparentpvid AND pv.pkg_id = pkg.pkg_id;

      parent_rec parent_cur%ROWTYPE;

      CURSOR patch_cur
      IS
         SELECT pv.*, pg.pkg_name
           FROM package_versions pv, PACKAGES pg
          WHERE pv.pkg_id = parpkg_id
            AND pv.pkg_version = snewpatchversion
            AND pv.pkg_id = pg.pkg_id;

      patch_rec  patch_cur%ROWTYPE;

      CURSOR releases_cur
      IS
         SELECT rc.pv_id
           FROM release_content rc
          WHERE rc.pv_id = patch_rec.pv_id;

      releases_rec releases_cur%ROWTYPE;
   BEGIN
      -- Get Last Install Order
      SELECT COUNT (*)
        INTO lastinstallorder
        FROM package_patches pp
       WHERE pp.pv_id = nparentpvid;

      -- Get parent details
      OPEN parent_cur;

      FETCH parent_cur
       INTO parent_rec;

      parpkg_id := parent_rec.pkg_id;

      -- Find if patch exists in database
      OPEN patch_cur;

      FETCH patch_cur
       INTO patch_rec;

      -- Parent must be official
      IF parent_rec.dlocked = 'Y'
      THEN
         IF patch_cur%NOTFOUND
         THEN
            ispatchdlocked := 'N';

            -- Create new patch version --
            SELECT seq_pv_id.NEXTVAL
              INTO patchpv_id
              FROM DUAL;

            split_version (snewpatchversion, ssv_mm, ssv_nmm, ssv_ext);

            INSERT INTO package_versions
                        (pv_id, pkg_id, pkg_version,
                         dlocked, created_stamp, creator_id,
                         modified_stamp, modifier_id, v_mm, v_nmm, v_ext,
                         src_path,
                         pv_description,
                         owner_id, is_patch, last_pv_id, build_type, is_build_env_required, bs_id,
                         is_autobuildable, ripple_field
                        )
                 VALUES (patchpv_id, parpkg_id, snewpatchversion,
                         ispatchdlocked, ora_sysdatetime, nuserid,
                         ora_sysdatetime, nuserid, ssv_mm, ssv_nmm, ssv_ext,
                         parent_rec.src_path,
                            'This is a patch to '
                         || parent_rec.pkg_name
                         || ' '
                         || parent_rec.pkg_version,
                         nuserid, 'Y', patchpv_id, 'M', 'N', 3, 'N', parent_rec.ripple_field
                        );

            INSERT INTO package_patches
                        (pv_id, patch_id, install_order)
                (SELECT nparentpvid AS pv_id, pv.pv_id AS patch_id,
                        lastinstallorder + 1 AS install_order
                   FROM package_versions pv
                  WHERE pv.pv_id = patchpv_id AND pv.is_patch = 'Y');

            /* LOG ACTION */
            log_action (patchpv_id,
                        'new_version',
                        nuserid,
                        'Patch version created: ' || snewpatchversion
                       );
            log_action (nparentpvid,
                        'patch_add',
                        nuserid,
                        'New patch created and attached: ' || snewpatchversion
                       );
         ELSE
            patchpv_id := patch_rec.pv_id;
            ispatchdlocked := patch_rec.dlocked;

            -- Find if pv_id exists in release content (i.e. it cannot be a patch)
            OPEN releases_cur;

            FETCH releases_cur
             INTO releases_rec;

            IF releases_cur%NOTFOUND
            THEN
               -- This pv_id is trully a patch, hence add Y to column IS_PATCH
               UPDATE package_versions
                  SET is_patch = 'Y'
                WHERE pv_id = patchpv_id;

               INSERT INTO package_patches
                           (pv_id, patch_id, install_order)
                   (SELECT nparentpvid AS pv_id, pv.pv_id AS patch_id,
                           lastinstallorder + 1 AS install_order
                      FROM package_versions pv
                     WHERE pv.pv_id = patchpv_id AND pv.is_patch = 'Y');
            END IF;

            CLOSE releases_cur;

            /* LOG ACTION */
            log_action (nparentpvid,
                        'patch_add',
                        nuserid,
                           'Patch version was found and attached: '
                        || snewpatchversion
                       );
         END IF;
      END IF;

      /* Create Patch Dependencies */
      opatchdepcollector := in_list_number (spatchidlist);

      -- Make sure patch is unofficial before altering its dependencies
      IF (opatchdepcollector.COUNT > 0) AND (ispatchdlocked = 'N')
      THEN
         -- Delete Existing Dependencies
         DELETE FROM package_dependencies dep
               WHERE dep.pv_id = patchpv_id;

         -- Insert new dependencies
         INSERT INTO package_dependencies
                     (pv_id, dpv_id, pkg_id, dpkg_id, build_type)
              SELECT patchpv_id AS pv_id, pv.pv_id AS dpv_id,
                     parpkg_id AS pkg_id, pv.pkg_id AS dpkg_id,
                     'L' AS build_type
                FROM package_versions pv
               WHERE pv.pv_id IN (
                      SELECT *
                        FROM TABLE
                                (CAST
                                    (opatchdepcollector AS relmgr_number_tab_t)
                                ));
      END IF;

      -- Return patch_id
      returnpatchid := patchpv_id;

      CLOSE parent_cur;

      CLOSE patch_cur;
   EXCEPTION
      WHEN DUP_VAL_ON_INDEX
      THEN
         raise_application_error (-20000,
                                     'Patch version '
                                  || snewpatchversion
                                  || ' already exist.'
                                 );
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE obsolete_patch (
      patchid            IN   NUMBER,
      isobsolete         IN   CHAR,
      obsoletecomments   IN   VARCHAR2,
      userid             IN   NUMBER
   )
   IS
   BEGIN
      -- Update patch
      UPDATE package_versions pv
         SET pv.is_obsolete = isobsolete,
             pv.obsolete_comments = obsoletecomments
       WHERE pv.pv_id = patchid;

      /*
      -- Update patch children
      UPDATE PACKAGE_VERSIONS pv SET
      pv.IS_OBSOLETE = IsObsolete,
      pv.OBSOLETE_COMMENTS = ObsoleteComments
      WHERE pv.PV_ID IN (
                     SELECT DISTINCT dep.DPV_ID
                       FROM PACKAGE_DEPENDENCIES dep
                      WHERE dep.PV_ID = PatchId
                     );


      -- Update patch parent
      UPDATE PACKAGE_VERSIONS pv SET
      pv.IS_OBSOLETE = IsObsolete,
      pv.OBSOLETE_COMMENTS = ObsoleteComments
      WHERE pv.PV_ID IN (
                     SELECT DISTINCT dep.PV_ID
                       FROM PACKAGE_DEPENDENCIES dep
                      WHERE dep.DPV_ID = PatchId
                     );

      */

      /* LOG ACTION */
      IF isobsolete IS NOT NULL
      THEN
         log_action (patchid,
                     'patch_obsolete',
                     userid,
                     'Obsolete patch. ' || obsoletecomments
                    );
      ELSE
         log_action (patchid,
                     'patch_obsolete',
                     userid,
                     'Undo patch obsolete.'
                    );
      END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE obsolete_patches (
      spatchidlist       IN   VARCHAR2,
      isobsolete         IN   CHAR,
      obsoletecomments   IN   VARCHAR2,
      userid             IN   NUMBER
   )
   IS
   BEGIN
      /*--------------- Business Rules Here -------------------*/
      IF spatchidlist IS NULL
      THEN
         raise_application_error (-20000,
                                  'Please select one or more Patches.'
                                 );
      END IF;

/*-------------------------------------------------------*/

      -- Update patch
      UPDATE package_versions pv
         SET pv.is_obsolete = isobsolete,
             pv.obsolete_comments = obsoletecomments
       WHERE pv.pv_id IN (
                SELECT *
                  FROM THE
                          (SELECT CAST
                                     (in_list_number (spatchidlist) AS relmgr_number_tab_t
                                     )
                             FROM DUAL
                          ));
      /*
      -- Update patch children
      UPDATE PACKAGE_VERSIONS pv SET
      pv.IS_OBSOLETE = IsObsolete,
      pv.OBSOLETE_COMMENTS = ObsoleteComments
      WHERE pv.PV_ID IN (
                     SELECT DISTINCT dep.DPV_ID
                       FROM PACKAGE_DEPENDENCIES dep
                      WHERE dep.PV_ID = PatchId
                     );


      -- Update patch parent
      UPDATE PACKAGE_VERSIONS pv SET
      pv.IS_OBSOLETE = IsObsolete,
      pv.OBSOLETE_COMMENTS = ObsoleteComments
      WHERE pv.PV_ID IN (
                     SELECT DISTINCT dep.PV_ID
                       FROM PACKAGE_DEPENDENCIES dep
                      WHERE dep.DPV_ID = PatchId
                     );

      */

      /* LOG ACTION
      IF IsObsolete IS NOT NULL THEN
         Log_Action ( PatchId, 'patch_obsolete', UserId,
                     'Obsolete patch. '|| ObsoleteComments );
      ELSE
         Log_Action ( PatchId, 'patch_obsolete', UserId,
                     'Undo patch obsolete.' );
      END IF;  */
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE add_process (
      nprocid         IN   processes.proc_id%TYPE,
      shealthtag      IN   processes.proc_name%TYPE,
      sprocdesc       IN   processes.proc_description%TYPE,
      scmdinterface   IN   processes.run_as%TYPE,
      spkgowner       IN   processes.pkg_owner%TYPE,
      sisinterface    IN   processes.is_interface%TYPE,
      npvid           IN   package_processes.pv_id%TYPE,
      nuserid         IN   NUMBER
   )
   IS
      pkgname   VARCHAR2 (100);

   BEGIN
      INSERT INTO processes
                  (proc_id, proc_name, proc_description, run_as, pkg_owner,
                   is_interface
                  )
           VALUES (nprocid, shealthtag, sprocdesc, scmdinterface, spkgowner,
                   sisinterface
                  );

      pk_package.add_package_process (nprocid, npvid, nuserid);
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE add_package_process (
      nprocidlist   IN   VARCHAR2,
      npvid         IN   package_processes.pv_id%TYPE,
      nuserid       IN   NUMBER
   )
   IS
      processname   VARCHAR2 (4000);

      CURSOR proc_cur
      IS
         SELECT prc.proc_id
           FROM processes prc
          WHERE prc.proc_id IN (
                   SELECT *
                     FROM THE
                             (SELECT CAST
                                        (in_list_number (nprocidlist) AS relmgr_number_tab_t
                                        )
                                FROM DUAL
                             ));

      proc_rec  proc_cur%ROWTYPE;
   BEGIN
      OPEN proc_cur;

      FETCH proc_cur
       INTO proc_rec;

      WHILE proc_cur%FOUND
      LOOP
         INSERT INTO package_processes (proc_id, pv_id)
              VALUES (proc_rec.proc_id, npvid);

         SELECT prc.proc_name
           INTO processname
           FROM processes prc
          WHERE prc.proc_id = proc_rec.proc_id;

         -- Log Action --
         log_action (npvid,
                     'process_add',
                     nuserid,
                     'Added process with health tag ' || processname
                    );

         FETCH proc_cur
          INTO proc_rec;
      END LOOP;

      CLOSE proc_cur;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE remove_process (
      nprocid   IN   package_processes.proc_id%TYPE,
      npvid     IN   package_processes.pv_id%TYPE,
      nuserid   IN   NUMBER
   )
   IS
      processname   VARCHAR2 (4000);
   BEGIN
      SELECT prc.proc_name
        INTO processname
        FROM processes prc
       WHERE prc.proc_id = nprocid;

      DELETE FROM package_processes
            WHERE proc_id = nprocid AND pv_id = npvid;

      -- Log Action --
      log_action (npvid,
                  'process_remove',
                  nuserid,
                  'Removed process with health tag ' || processname
                 );
   END;
/*-------------------------------------------------------------------------------------------------------*/
   /*
   ** Author: Rupesh Solanki
   ** Purpose: To move package versions from one release to another
   ** Release: 4th September 2006
   */
   PROCEDURE move_package (
      npvid        IN package_versions.pv_id%TYPE,
      nrtagid      IN release_tags.rtag_id%TYPE,
      nnewrtagid   IN release_tags.rtag_id%TYPE,
      nuserid      IN NUMBER
   )
   IS

      oldrtag_name VARCHAR2(4000);newrtag_name VARCHAR2(4000);

   BEGIN
      SELECT rtag_name into oldrtag_name
      FROM RELEASE_TAGS
      WHERE rtag_id = nrtagid;

      SELECT rtag_name into newrtag_name
      FROM RELEASE_TAGS
      WHERE rtag_id = nnewrtagid;

      /* Table Work In Progress*/
      UPDATE WORK_IN_PROGRESS
      SET RTAG_ID = nnewrtagid
      WHERE RTAG_ID = nrtagid
      AND PV_ID = npvid;

      /* Table PLANNED*/
      UPDATE PLANNED
      SET RTAG_ID = nnewrtagid
      WHERE RTAG_ID = nrtagid
      AND PV_ID = npvid;

      /* Table PEGGED_VERSIONS */
      DELETE FROM PEGGED_VERSIONS pegv
      WHERE pegv.RTAG_ID = nrtagid
      AND pegv.PV_ID = npvid;

      /* Table ADVISORY_RIPPLE*/
      DELETE FROM ADVISORY_RIPPLE
      WHERE RTAG_ID = nrtagid
      AND PV_ID = npvid;


      -- Log Action --
      log_action (npvid,
                  'move_package_version',
                  nuserid,
                  'Moved package version from ' || oldrtag_name || ' to ' || newrtag_name
                 );
   END;

/*-------------------------------------------------------------------------------------------------------*/
   /*
   ** Author: Rupesh Solanki
   ** Purpose: To modify the product state from integration to test to deployment
   ** Release: 25th January 2006
   */
   PROCEDURE modify_product_state (
      npvid    IN package_versions.pv_id%TYPE,
      nrtagid  IN release_tags.rtag_id%TYPE,
      nstateid IN product_states.state_id%TYPE,
      nuserid  IN NUMBER
   ) IS

      sStateName VARCHAR2(4000);
      sRtagName VARCHAR2(4000);

   BEGIN

      UPDATE RELEASE_CONTENT
      SET PRODUCT_STATE = nstateid
      WHERE PV_ID = npvid
      AND RTAG_ID = nrtagid;


      SELECT STATE INTO sStateName
      FROM PRODUCT_STATES
      WHERE STATE_ID = nstateid;

      SELECT RTAG_NAME into sRtagName
      FROM RELEASE_TAGS
      WHERE RTAG_ID = nrtagid;


      -- Log Action --
      log_action (npvid,
                  'modify_product_state',
                     nuserid,
                     sStateName || ' in '|| sRtagName
                  );
   END;
/*-------------------------------------------------------------------------------------------------------*/
   /*
   ** Author: Jeremy Tweddle
   ** Date: 24/Aug/2007
   */
   PROCEDURE add_code_review_url (
      npvid           IN    NUMBER,
      nprojid         IN    NUMBER,
      surl            IN    VARCHAR2,
      sreason         IN    VARCHAR2,
      ddateofreview   IN    VARCHAR2
   ) IS

      ncrid NUMBER;

   BEGIN

      SELECT seq_cr_id.NEXTVAL INTO ncrid FROM DUAL;

      INSERT INTO code_review_url ( cr_id, pv_id, proj_id, url, reason, date_of_review, last_modified )
      VALUES ( ncrid, npvid, nprojid, surl, sreason, TO_DATE( ddateofreview,'DD/MM/YYYY' ), ora_sysdatetime );

   END;
/*-------------------------------------------------------------------------------------------------------*/
   /*
   ** Author: Jeremy Tweddle
   ** Date: 22/Aug/2007
   */
   PROCEDURE update_code_review_url (
      ncrid           IN    NUMBER,
      nprojid         IN    NUMBER,
      surl            IN    VARCHAR2,
      sreason         IN    VARCHAR2,
      ddateofreview   IN    VARCHAR2
   ) IS

   BEGIN

      UPDATE code_review_url
      SET url = surl,
          proj_id = nprojid,
          reason = sreason,
          date_of_review = TO_DATE( ddateofreview,'DD/MM/YYYY' ),
          last_modified = ora_sysdatetime
      WHERE cr_id = ncrid;

   END;

/*-------------------------------------------------------------------------------------------------------*/
   /*
   ** Author: Jeremy Tweddle
   ** Date: 22/Aug/2007
   */
   PROCEDURE remove_code_review_url (
      ncrid  IN    NUMBER
   ) IS

   BEGIN
      DELETE FROM code_review_url
      WHERE cr_id = ncrid;
   END;
/*-------------------------------------------------------------------------------------------------------*/

PROCEDURE
        SET_RIPPLE_STOP (
        nPVID IN RELEASE_CONTENT.PV_ID%TYPE,
        nRtagId IN RELEASE_CONTENT.RTAG_ID%TYPE,
        nUserId IN NUMBER,
        cMode IN CHAR
    ) IS
    ReleaseLocation VARCHAR2(4000);
    sMode VARCHAR(100);
    cData CHAR;
    

BEGIN

    IF (nPVID IS NULL) THEN
        RAISE_APPLICATION_ERROR (-20000, 'PvId not set' );
    END IF;

    IF (nRtagId IS NULL) THEN
        RAISE_APPLICATION_ERROR (-20001, 'rTagId not set' );
    END IF;

    cData := cMode;
    If cMode = 's' THEN
        sMode := 'ripple_stop';

    ELSIF cMode = 'w' THEN
        sMode := 'ripple_wait';

    ELSIF cMode = 'r' THEN
        sMode := 'ripple_removed';
        cData := NULL;

    ELSIF cMode = 'g' THEN
        sMode := 'ripple_resume';

    ELSE
       RAISE_APPLICATION_ERROR (-20002, 'Unknown mode:' || cMode );

    END IF;

    -- Update the value
    UPDATE RELEASE_CONTENT 
    SET RIPPLE_STOP = cData
    WHERE RTAG_ID = nRtagId
    AND PV_ID = nPVID;

    -- Mark Release Changed for build
    PK_RELEASE.SET_RELEASE_MODIFIED(nRtagId);

    /* LOG ACTION */
    SELECT proj.PROJ_NAME ||' / '|| rt.RTAG_NAME INTO ReleaseLocation
    FROM PROJECTS proj,RELEASE_TAGS rt
    WHERE rt.PROJ_ID = proj.PROJ_ID
    AND rt.RTAG_ID = nRtagId;

    Log_Action ( nPVID, sMode, nUserId, 'Location: '|| ReleaseLocation);

END SET_RIPPLE_STOP;

END pk_package;

/

  GRANT EXECUTE ON "RELEASE_MANAGER"."PK_PACKAGE" TO "DEPLOYMENT_MANAGER";
  GRANT DEBUG ON "RELEASE_MANAGER"."PK_PACKAGE" TO "DEPLOYMENT_MANAGER";
--------------------------------------------------------
--  DDL for Package Body PK_PLANNED
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE BODY "RELEASE_MANAGER"."PK_PLANNED" IS

/*
------------------------------
||  Last Modified:  G.Huddy
||  Modified Date:  05/Aug/2008
||  Body Version:   1.2
------------------------------
*/


/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE ADD_PACKAGE ( newPvId IN NUMBER, ViewId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER, OPR IN CHAR DEFAULT 'R' ) IS

    oldPvId NUMBER;
    ReleaseLocation VARCHAR2(4000);
    IsPatch CHAR(1) := NULL;
    sLocation VARCHAR2(4000) := NULL;
    nRtagIdLocation NUMBER;



BEGIN
    /*--------------- Business Rules Here -------------------*/
    /*-------------------------------------------------------*/

    IF OPR = 'R' THEN
      BEGIN
          -- Check if Exists in "Work in progress" anywhere in the world, except "Closed mode" releases
          SELECT proj.PROJ_NAME ||' > '|| rt.RTAG_NAME, rt.RTAG_ID  INTO sLocation, nRtagIdLocation
            FROM PLANNED pl,
                 RELEASE_TAGS rt,
                 PROJECTS proj
           WHERE pl.PV_ID = newPvId
             AND pl.RTAG_ID = rt.RTAG_ID
             AND rt.OFFICIAL != 'Y'
             AND rt.PROJ_ID = proj.PROJ_ID;

          EXCEPTION
              WHEN NO_DATA_FOUND THEN
                  sLocation := NULL;
      END;

      IF (sLocation IS NULL) OR (nRtagIdLocation = RtagId) THEN

          -- Add to "Pending" area
          INSERT INTO PLANNED ( RTAG_ID, PV_ID, VIEW_ID, OPERATION )
          VALUES( RtagId, newPvId, ViewId, OPR );

          /* LOG ACTION */
          SELECT proj.PROJ_NAME ||' / '|| rt.RTAG_NAME INTO ReleaseLocation
            FROM PROJECTS proj,
                 RELEASE_TAGS rt
           WHERE rt.PROJ_ID = proj.PROJ_ID
             AND rt.RTAG_ID = RtagId;

          Log_Action ( newPvId, 'add_to_planned', UserId, 'Location: '|| ReleaseLocation );

      ELSE
            RAISE_APPLICATION_ERROR (-20000, 'This version is already in Pending Area at '|| sLocation ||'.' );
        END IF;

    ELSE
      -- Not adding a WIP. Merging a package version
      MERGE_PACKAGE ( newPvId, ViewId, RtagId, UserId, OPR );
    END IF;

END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE REMOVE_PACKAGE ( PvId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER ) IS

    ReleaseLocation VARCHAR2(4000);

BEGIN

    /*--------------- Business Rules Here -------------------*/
    /*-------------------------------------------------------*/


    -- Get release location for logging pusposes
    SELECT proj.PROJ_NAME  ||' / '|| rt.RTAG_NAME INTO ReleaseLocation
      FROM PROJECTS proj,
           RELEASE_TAGS rt
     WHERE rt.PROJ_ID = proj.PROJ_ID
       AND rt.RTAG_ID = RtagId;

    -- Ensure that package is not marked as Pending any more
    UPDATE package_versions
       SET DLOCKED  = 'N'
     WHERE PV_ID  = PvId
       AND DLOCKED != 'Y';

    -- Delete from Work In Progress
    DELETE
      FROM PLANNED pl
     WHERE pl.RTAG_ID = RtagId
       AND pl.PV_ID = PvId;

    Log_Action ( PvId, 'deleted_from_pending', UserId, 'Location: '|| ReleaseLocation );




END;
/*-------------------------------------------------------------------------------------------------------*/
FUNCTION GET_PACKAGE_VIEW ( PvId IN NUMBER, RtagId IN NUMBER ) RETURN NUMBER IS

    ReturnValue NUMBER;

BEGIN
    SELECT pl.VIEW_ID INTO ReturnValue
      FROM PLANNED pl
     WHERE pl.RTAG_ID = RtagId
       AND pl.PV_ID = PvId;

    RETURN ReturnValue;
END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE GET_VIEW_CONTENT ( RtagId IN NUMBER, ViewId IN NUMBER, RecordSet OUT typeCur ) as 
begin
OPEN RecordSet FOR
-- Determine the PV_ID and OPERATION for the required VIEW
With selectedPv as (
    SELECT pv.pv_id, rel.operation, 0 as pkg_state
      FROM PLANNED rel, package_versions pv, VIEW_DEF vd,  VIEWS vi
      WHERE rel.pv_id = pv.pv_id
      AND vd.PKG_ID = pv.PKG_ID
      AND vd.VIEW_ID = ViewId
      AND rel.RTAG_ID = RtagId
      AND vi.VIEW_ID = ViewId
      AND vi.BASE_VIEW NOT IN ('Y', 'S')
    UNION
     SELECT rel.pv_id, rel.operation, 0 as pkg_state
     FROM PLANNED rel, VIEWS vi
     WHERE rel.VIEW_ID = ViewId
     AND rel.RTAG_ID = RtagId
     AND vi.VIEW_ID = ViewId
     AND vi.BASE_VIEW IN ('Y', 'S')
),
-- Determine packages that are building
building as (
    SELECT unique rl.CURRENT_PV_ID as pv_id, rc.RTAG_ID 
    FROM RELEASE_CONFIG rc, RELEASE_TAGS rt, RUN_LEVEL rl 
    WHERE rt.RTAG_ID = rc.RTAG_ID
    AND rc.RTAG_ID = RtagId
    AND rc.bmcon_id is not null
    AND rt.OFFICIAL in ( 'N', 'R', 'C')
    AND rl.RCON_ID(+) = rc.RCON_ID
    AND rl.CURRENT_PKG_ID_BEING_BUILT is not null
    AND NVL(rl.PAUSE,0) < 2
), 
-- Determine Packages that are scheduled to build    
scheduled as (
    SELECT pv_id, RTAG_ID from daemon_instructions di
    WHERE di.op_code = 2
    AND RTAG_ID = RtagId
) , 
-- Determine Packages that failed to build or have been excluded
buildFail as (
    SELECT pv_id, root_pv_id, RTAG_ID from do_not_ripple dnr
    WHERE RTAG_ID = RtagId
) 
-- Generate the complete dataset from the fragments
  SELECT Case
                    When sdi.pv_id is not null then 14
                    When bb.pv_id is not null then 15
                    When bf.pv_id is not null AND bf.root_pv_id is NULL then 16
                    When bf.pv_id is not null AND bf.root_pv_id is NOT NULL then  17
                    When rel.pkg_state is not null then rel.pkg_state
                    Else 0
                End as pkg_state,
               NULL AS DEPRECATED_STATE,
               pv.pv_id,
               pkg.pkg_name,
               pv.pkg_version,
               pv.dlocked,
               pv.pv_description,
               pv.BUILD_TYPE,
               rel.operation
          FROM selectedPv rel,
               packages pkg,
               package_versions pv,
               scheduled sdi,
               buildFail bf,
               building bb
         WHERE pv.pkg_id = pkg.pkg_id
           AND rel.pv_id = pv.pv_id
           AND sdi.pv_id(+) = rel.pv_id
           AND bf.pv_id(+) = rel.pv_id
           AND bb.pv_id(+) = rel.pv_id
         ORDER BY UPPER(pkg.PKG_NAME), pv.pv_id;
END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE CHANGE_PACKAGE_VIEW ( PvId IN NUMBER, RtagId IN NUMBER, NewViewId IN NUMBER ) IS

BEGIN

    UPDATE PLANNED pl SET
    pl.VIEW_ID = NewViewId
    WHERE pl.PV_ID = PvId
      AND pl.RTAG_ID = RtagId;

END;
/*-------------------------------------------------------------------------------------------------------*/
-- DEVI-45275 This new function supports the ability to insert into the planned table, and existing
-- version of a package as part of a release-to-release merge operation carried out within release manager.
-- DEVI-49594 This function has subsequently been changed to allow a merge operation to cancel its
-- opposite operation, if the opposite already exists in the planned table. This supports user activity
-- via the Release Manager merge manager display

PROCEDURE MERGE_PACKAGE ( newPvId IN NUMBER, ViewId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER, mergeOperation IN CHAR ) IS

    ReleaseLocation VARCHAR2(4000);

        entryExists NUMBER;
        existingOperation CHAR;
BEGIN
    /*--------------- Business Rules Here -------------------*/
    /*-------------------------------------------------------*/

      -- Determine if the specified PV_ID already exists in the planned table....
      SELECT COUNT (pl.pv_id) INTO entryExists
      FROM PLANNED pl
      WHERE pl.pv_id = newPvId
      AND pl.rtag_id = RtagId
      AND pl.view_id = ViewId;

      -- If the specified PV_ID already exists in the planned table....
      IF entryExists = 1 THEN

         -- Get the operation for the existing entry
         SELECT pl.operation INTO existingOperation
         FROM PLANNED pl
         WHERE pl.pv_id = newPvId
         AND pl.rtag_id = RtagId
         AND pl.view_id = ViewId;

         -- Is the specified merge operation the opposite of the existing entry?
         -- If it is not, then there is nothing to do, otherwise...
         -- NOTE: A = Add, S = Subtract
         IF (mergeOperation = 'S' AND existingOperation = 'A')
            OR (mergeOperation = 'A' AND existingOperation = 'S') THEN

           -- It is the opposite, so effectively it cancels the existing entry
           -- Remove the entry from the planned table
           DELETE
            FROM PLANNED pl
           WHERE pl.pv_id = newPvId
             AND pl.rtag_id = RtagId
             AND pl.view_id = ViewId;

           -- Log action
           SELECT proj.PROJ_NAME ||' / '|| rt.RTAG_NAME INTO ReleaseLocation
             FROM PROJECTS proj,
                  RELEASE_TAGS rt
            WHERE rt.PROJ_ID = proj.PROJ_ID
              AND rt.RTAG_ID = RtagId;

           Log_Action ( newPvId, 'deleted_from_pending', UserId, 'Location: '|| ReleaseLocation );
         END IF;
      ELSE
         -- Add to Planned tabled
         INSERT INTO PLANNED ( RTAG_ID, PV_ID, VIEW_ID, OPERATION )
         VALUES( RtagId, newPvId, ViewId, mergeOperation );

         -- Log Action
         SELECT proj.PROJ_NAME ||' / '|| rt.RTAG_NAME INTO ReleaseLocation
          FROM PROJECTS proj,
               RELEASE_TAGS rt
         WHERE rt.PROJ_ID = proj.PROJ_ID
         AND   rt.RTAG_ID = RtagId;

         Log_Action ( newPvId, 'add_to_planned', UserId, 'Location: '|| ReleaseLocation );
      END IF;

END;
/*-------------------------------------------------------------------------------------------------------*/
END PK_PLANNED;

/
--------------------------------------------------------
--  DDL for Package Body PK_PROJECT
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE BODY "RELEASE_MANAGER"."PK_PROJECT" IS

    /*------------------------------------------------------------------------*/
    PROCEDURE update_base_url (
    nprojid   IN  projects.proj_id%TYPE,
    sbaseurl  IN  VARCHAR2
    ) IS
    BEGIN

    UPDATE projects
    SET base_url = sbaseurl
    WHERE proj_id = nprojid;

    END update_base_url;

/*------------------------------------------------------------------------*/
    PROCEDURE update_project_config (
    nprojid   IN  projects.proj_id%TYPE,
    sbaseurl  IN  VARCHAR2,
    sjirakey  IN  VARCHAR2
    ) IS
    BEGIN

    UPDATE projects
    SET base_url = sbaseurl,
        jira_key = sjirakey
    WHERE proj_id = nprojid;

    END update_project_config;
    /*------------------------------------------------------------------------*/

    END pk_project;

/
--------------------------------------------------------
--  DDL for Package Body PK_RELEASE
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE BODY "RELEASE_MANAGER"."PK_RELEASE" IS

/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE New_Release ( sReleaseName IN VARCHAR2,
                        sReleaseComments IN VARCHAR2,
                        nProjId IN NUMBER,
                        nSourceRtagId IN NUMBER,
                        sIsBranched IN CHAR,
                        nUserId IN NUMBER,
                        cOfficial IN CHAR DEFAULT 'N'
                        ) IS

RtagId NUMBER;
ParentRtagId NUMBER;
RecCount NUMBER := 0;
VtreeId NUMBER;

BEGIN
   /*--------------- Business Rules Here -------------------*/
   -- Check for missing parameters
   IF (sReleaseName IS NULL) OR (nUserId IS NULL)
   THEN
      RAISE_APPLICATION_ERROR (-20000, 'Missing some parameters! sReleaseName= '|| sReleaseName ||', nUserId='|| nUserId );

   END IF;


   -- Check for duplicate Release Names
   SELECT COUNT(rt.RTAG_ID) INTO RecCount
     FROM RELEASE_TAGS rt
    WHERE UPPER( rt.RTAG_NAME ) = UPPER( sReleaseName )
      AND rt.PROJ_ID = nProjId;

   IF (RecCount > 0) THEN
      RAISE_APPLICATION_ERROR (-20000, 'Release Name '|| sReleaseName ||' is Already Used in this Project.');
   END IF;
   /*-------------------------------------------------------*/


   -- Get rtag_id
   SELECT SEQ_RTAG_ID.NEXTVAL INTO RtagId FROM DUAL;

   SELECT SEQ_VTREE_ID.NEXTVAL INTO VtreeId FROM DUAL;



   -- Get Parent RtagId
   ParentRtagId := GET_PARENT_RTAG ( RtagId, nSourceRtagId, sIsBranched );

   -- If the parent RTAG is NOT in this project then we cannot use it.
   -- We must re-assign the parent to be the new release's RTAG_ID instead
   -- else it will not show up in the projects release tree (DEVI-55480)
   SELECT COUNT(rt.RTAG_ID) INTO RecCount
     FROM RELEASE_TAGS rt
    WHERE rt.RTAG_ID = ParentRtagId
      AND rt.PROJ_ID = nProjId;

   IF (RecCount = 0) THEN
     ParentRtagId := RtagId;
   END IF;

   -- Create new release
   INSERT INTO RELEASE_TAGS ( RTAG_ID, RTAG_NAME, DESCRIPTION, CREATED_STAMP, CREATOR_ID,
                        OFFICIAL, REBUILD_ENV, REBUILD_STAMP,
                        PARENT_RTAG_ID, PROJ_ID, VTREE_ID )
   VALUES ( RtagId,
          sReleaseName,
          sReleaseComments,
          ora_sysdatetime,
          nUserId,
          cOfficial,
          'N',
          0,
          ParentRtagId,
          nProjId,
          VtreeId );

   -- If a source release is provided, clone its config spec branch information into the new release (DEVI-56650)
   IF (NOT nSourceRtagId IS NULL)
   THEN
      UPDATE RELEASE_TAGS rtd
      SET rtd.config_spec_branch = (SELECT rts.CONFIG_SPEC_BRANCH FROM RELEASE_TAGS rts WHERE rts.RTAG_ID = nSourceRtagId)
      WHERE rtd.RTAG_ID = RtagId;
   END IF;

   -- Update display Order
   UPDATE_DISPLAY_ORDER ( nProjId );

   /* Log Project Action */
   Log_Project_Action ( nProjId, 'new_release', nUserId, sReleaseName, RtagId );


   -- Import Release Contents
   IF (NOT nSourceRtagId IS NULL) THEN
      Import_Release_Contents ( nSourceRtagId, RtagId, nUserId, 1 );
   END IF;

END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE UPDATE_DISPLAY_ORDER ( nProjId IN NUMBER ) IS


BEGIN


   /*--------------- Business Rules Here -------------------*/
   /*-------------------------------------------------------*/

   UPDATE RELEASE_TAGS urt SET
   urt.DISPLAY_ORDER = (
                  SELECT qry.REC_NUM
                    FROM (
                        SELECT rel.*, ROWNUM AS REC_NUM
                          FROM (

                                SELECT rt.RTAG_ID,
                                    rt.DISPLAY_ORDER,
                                     DECODE( rt.PARENT_RTAG_ID,
                                             rt.RTAG_ID, 0, rt.PARENT_RTAG_ID ) AS PARENT_RTAG_ID
                                FROM RELEASE_TAGS rt
                               WHERE rt.PROJ_ID = nProjId

                                ) rel
                        START WITH rel.PARENT_RTAG_ID = 0
                        CONNECT BY PRIOR rel.RTAG_ID = rel.PARENT_RTAG_ID
                        ORDER SIBLINGS BY rel.DISPLAY_ORDER
                        ) qry
                     WHERE qry.RTAG_ID = urt.RTAG_ID
                  )
   WHERE urt.PROJ_ID = nProjId;

END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE MOVE_RELEASE ( sRtagIdList IN VARCHAR2, nProjId IN NUMBER, nUserId IN NUMBER  ) IS

   nIdCollector RELMGR_NUMBER_TAB_t := RELMGR_NUMBER_TAB_t();
   SeqNum NUMBER;

BEGIN


   /*--------------- Business Rules Here -------------------*/
   /*-------------------------------------------------------*/

   nIdCollector := IN_LIST_NUMBER ( sRtagIdList );

   -- Set start sequence number
   SeqNum := 1;

   FOR i IN 1..nIdCollector.COUNT
   LOOP

      -- Update new display order
      UPDATE RELEASE_TAGS rt SET
         rt.DISPLAY_ORDER = SeqNum
       WHERE rt.PROJ_ID = nProjId
         AND rt.RTAG_ID = nIdCollector(i);

      SeqNum := SeqNum + 1;

   END LOOP;

END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE Update_Release ( nRtagId IN NUMBER,
                           sReleaseName IN VARCHAR2,
                           sReleaseComments IN VARCHAR2,
                           nParentRtagId IN NUMBER,
                           nMASSRtagId IN NUMBER,
                           nConfigSpecBranch IN VARCHAR2,
                           sOwnerEmail IN VARCHAR2,
                           nUserId IN NUMBER,
                           cState IN VARCHAR,
                           nBuildAge in NUMBER,
                           cLxr in CHAR) IS

RecCount NUMBER := 0;
ProjId NUMBER;

BEGIN


   /*--------------- Business Rules Here -------------------*/
   -- Check for missing parameters
   IF (sReleaseName IS NULL) OR (nUserId IS NULL) OR (nRtagId IS NULL)
   THEN
      RAISE_APPLICATION_ERROR (-20000, 'Missing some parameters! sReleaseName= '|| sReleaseName ||', nUserId='|| nUserId ||', nRtagId='|| nRtagId);

   END IF;


   -- Check for duplicate Release Names
   SELECT rt.PROJ_ID INTO ProjId
     FROM RELEASE_TAGS rt
    WHERE rt.RTAG_ID = nRtagId;

   SELECT COUNT(rt.RTAG_ID) INTO RecCount
     FROM RELEASE_TAGS rt
    WHERE UPPER( rt.RTAG_NAME ) = UPPER( sReleaseName )
      AND rt.RTAG_ID != nRtagId
      AND rt.PROJ_ID = ProjId;


   IF (RecCount > 0) THEN
      RAISE_APPLICATION_ERROR (-20000, 'Release Name '|| sReleaseName ||' is Already Used in this Project.');
   END IF;
   /*-------------------------------------------------------*/



   -- Update release details
   UPDATE RELEASE_TAGS rt SET
   rt.RTAG_NAME = sReleaseName,
   rt.DESCRIPTION = sReleaseComments,
   rt.PARENT_RTAG_ID = nParentRtagId,
   rt.ASSOC_MASS_REF = nMASSRtagId,
   rt.CONFIG_SPEC_BRANCH = nConfigSpecBranch,
   rt.OWNER_EMAIL = sOwnerEmail,
   rt.PRODUCT_STATE_USED = cState,
   rt.BUILD_AGE = nBuildAge,
   rt.LXR = cLxr
   WHERE rt.RTAG_ID = nRtagId;

   -- Update display Order
   UPDATE_DISPLAY_ORDER ( ProjId );

   /* Log Project Action */
   Log_Project_Action ( ProjId, 'update_release', nUserId, 'Release Name: <br>Release Comments:', nRtagId );




END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE Destroy_Release ( nRtagId IN NUMBER, nUserId IN NUMBER ) IS

   RecCount NUMBER := 0;
   sReleaseId VARCHAR2(4000);
   ProjId NUMBER;

BEGIN
   /*--------------- Business Rules Here -------------------*/
   IF (nRtagId IS NULL)
   THEN
      RAISE_APPLICATION_ERROR (-20000, 'Missing some parameters! nRtagId= '|| nRtagId  );
   END IF;



   -- Check for any kids
   SELECT COUNT( rt.RTAG_ID ) INTO RecCount
     FROM RELEASE_TAGS rt
    WHERE rt.PARENT_RTAG_ID = nRtagId
      AND rt.RTAG_ID != rt.PARENT_RTAG_ID;

   IF (RecCount > 0) THEN
      RAISE_APPLICATION_ERROR (-20000, 'Cannot destroy this release. You need to destroy its children releases first.'  );
   END IF;
   /*-------------------------------------------------------*/

   -- Clear the release contents
   Clean_Release_Contents ( nRtagId, nUserId );

   /* Log Project Action */
   SELECT rt.PROJ_ID, rt.RTAG_NAME ||'['|| rt.RTAG_VERSION ||'.'|| rt.RTAG_LIFE_CYCLE ||']' INTO ProjId, sReleaseId
     FROM RELEASE_TAGS rt
    WHERE rt.RTAG_ID = nRtagId;

   Log_Project_Action ( ProjId, 'destroy_release', nUserId, sReleaseId, nRtagId );


   -- Remove Release
   DELETE
     FROM RELEASE_TAGS rt
    WHERE rt.RTAG_ID = nRtagId;



END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE Import_Release_Contents ( nSourceRtagId IN NUMBER, nTargetRtagId IN NUMBER, nUserId IN NUMBER, nMode IN NUMBER default 0 ) IS

   sSourceLocation VARCHAR2(4000);
   sTargetLocation VARCHAR2(4000);
   ProjId NUMBER;
   nIsOpen NUMBER;
   RconId NUMBER;

   -- this cursor gets the source release daemon configurations, ensuring that the
   -- first record will be the master daemon, and subsequent records will be the slaves.
   CURSOR curSrcReleaseConfigs IS
    SELECT daemon_hostname, gbe_id, gbe_buildfilter, bmcon_id, daemon_mode
     FROM RELEASE_CONFIG rc
    WHERE rc.RTAG_ID = nSourceRtagId
    ORDER BY rc.daemon_mode;
    recSrcReleaseConfigs curSrcReleaseConfigs%ROWTYPE;

    -- this cursor looks for target release daemons
   CURSOR curTgtReleaseConfigs IS
    SELECT rcon_id
     FROM RELEASE_CONFIG rc
    WHERE rc.RTAG_ID = nTargetRtagId;
    recTgtReleaseConfigs curTgtReleaseConfigs%ROWTYPE;

    -- this cursor looks for target release daemon run level entries
   CURSOR curTgtReleaseConfigRunLevel IS
    SELECT pause
     FROM RUN_LEVEL rl
    WHERE rl.RCON_ID = recTgtReleaseConfigs.rcon_id;
    recTgtReleaseConfigRunLevel curTgtReleaseConfigRunLevel%ROWTYPE;

BEGIN
   /*--------------- Business Rules Here -------------------*/
   IF (nSourceRtagId IS NULL) OR (nTargetRtagId IS NULL)
   THEN
      RAISE_APPLICATION_ERROR (-20000, 'Missing some parameters! nSourceRtagId= '|| nSourceRtagId ||', nTargetRtagId='|| nTargetRtagId );
   END IF;

   IF (nSourceRtagId = nTargetRtagId) THEN
      RAISE_APPLICATION_ERROR (-20000, 'Cannot import release contents from same release.' );
   END IF;


   -- Check if Target release is in OPEN-ish mode
   IF nMode = 0 THEN
     SELECT count(*)  INTO  nIsOpen
       FROM RELEASE_TAGS rt
      WHERE rt.RTAG_ID = nTargetRtagId
      AND rt.OFFICIAL in ('N', 'R', 'C');

     IF (nIsOpen > 1) THEN
        RAISE_APPLICATION_ERROR (-20000, 'Release must be in OPEN mode to import the contents.' );
     END IF;
  END IF;

   -- check that the target release's daemons are all paused before we allow an import operation
   OPEN curTgtReleaseConfigs;
   FETCH curtgtReleaseConfigs INTO recTgtReleaseConfigs;


   WHILE curTgtReleaseConfigs%FOUND
   LOOP
      OPEN curTgtReleaseConfigRunLevel;
      FETCH curTgtReleaseConfigRunLevel INTO recTgtReleaseConfigRunLevel;
      IF curTgtReleaseConfigRunLevel%FOUND THEN
         IF (recTgtReleaseConfigRunLevel.pause IS NULL) OR
            (recTgtReleaseConfigRunLevel.pause <> 2) THEN
            RAISE_APPLICATION_ERROR (-20000, 'Destination release daemon run levels must be paused before operation can proceed.' );
         END IF;
      ELSE
         -- we don't know what the daemon run level is so err on the side of caution
         RAISE_APPLICATION_ERROR (-20000, 'Destination release daemon run levels must be paused before operation can proceed.' );
      END IF;
      CLOSE curTgtReleaseConfigRunLevel;

      FETCH curTgtReleaseConfigs INTO recTgtReleaseConfigs;
   END LOOP;

   CLOSE curTgtReleaseConfigs;


   /*-------------------------------------------------------*/

   -- Clean target contents
   Clean_Release_Contents ( nTargetRtagId, nUserId );

   -- Import Released Area Contents
   INSERT INTO RELEASE_CONTENT ( RTAG_ID, PV_ID, BASE_VIEW_ID, INSERT_STAMP, INSERTOR_ID, PKG_STATE, PKG_ID, DEPRECATED_STATE,PRODUCT_STATE,SDKTAG_ID )
   SELECT nTargetRtagId AS RTAG_ID,
         rc.PV_ID,
         rc.BASE_VIEW_ID,
         rc.INSERT_STAMP,
         rc.INSERTOR_ID,
         rc.PKG_STATE,
         rc.PKG_ID,
         rc.DEPRECATED_STATE,
         rc.PRODUCT_STATE,
         rc.SDKTAG_ID
     FROM RELEASE_CONTENT rc
    WHERE rc.RTAG_ID = nSourceRtagId;


   -- Import any Pegged Version settings from the source release
   INSERT INTO PEGGED_VERSIONS ( RTAG_ID, PV_ID )
   SELECT nTargetRtagId AS RTAG_ID,
          pegv.PV_ID
     FROM PEGGED_VERSIONS pegv
    WHERE pegv.RTAG_ID = nSourceRtagId;

   -- Import any Advisory Ripple settings from the source release
   INSERT INTO ADVISORY_RIPPLE ( RTAG_ID, PV_ID )
   SELECT nTargetRtagId AS RTAG_ID,
          avr.PV_ID
     FROM ADVISORY_RIPPLE avr
    WHERE avr.RTAG_ID = nSourceRtagId;

   -- Import Ignore Warning states
   INSERT INTO IGNORE_WARNINGS ( RTAG_ID, PV_ID, DPV_ID )
   SELECT nTargetRtagId AS RTAG_ID,
          igw.PV_ID,
          igw.DPV_ID
     FROM IGNORE_WARNINGS igw
    WHERE igw.rtag_id = nSourceRtagId;


   --Import Release Configuration Information
   OPEN curSrcReleaseConfigs;
   FETCH curSrcReleaseConfigs INTO recSrcReleaseConfigs;

   WHILE curSrcReleaseConfigs%FOUND
   LOOP
      -- add a daemon to the target release
      PK_BUILDAPI.duplicate_daemon_config( nTargetRtagId,
                                     recSrcReleaseConfigs.bmcon_id,
                                     recSrcReleaseConfigs.daemon_hostname,
                                     recSrcReleaseConfigs.gbe_id,
                                     recSrcReleaseConfigs.daemon_mode ,
                                     recSrcReleaseConfigs.gbe_buildfilter );

      FETCH curSrcReleaseConfigs INTO recSrcReleaseConfigs;
   END LOOP;
   CLOSE curSrcReleaseConfigs;

   /* Log Project Action */
   -- Get Source Location
   SELECT pr.PROJ_NAME ||' > '|| rt.RTAG_NAME ||' ['|| rt.RTAG_VERSION ||'.'|| rt.RTAG_LIFE_CYCLE ||']'  INTO sSourceLocation
     FROM RELEASE_TAGS rt,
           PROJECTS pr
    WHERE rt.PROJ_ID = pr.PROJ_ID
      AND rt.RTAG_ID = nSourceRtagId;

   -- Get Target Location
   SELECT pr.PROJ_NAME ||' > '|| rt.RTAG_NAME ||' ['|| rt.RTAG_VERSION ||'.'|| rt.RTAG_LIFE_CYCLE ||']'  INTO sTargetLocation
     FROM RELEASE_TAGS rt,
           PROJECTS pr
    WHERE rt.PROJ_ID = pr.PROJ_ID
      AND rt.RTAG_ID = nTargetRtagId;

   -- Get project id
   SELECT rt.PROJ_ID  INTO  ProjId
     FROM RELEASE_TAGS rt
    WHERE rt.RTAG_ID = nTargetRtagId;

   Log_Project_Action ( ProjId, 'import_release_contents', nUserId, 'SOURCE: '|| sSourceLocation ||'   TARGET: '|| sTargetLocation, nTargetRtagId );
END;


/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE Clean_Release_Contents ( nRtagId IN NUMBER, nUserId IN NUMBER ) IS

   RecCount NUMBER;
        rconIdList VARCHAR2(4000);

BEGIN
   /*--------------- Business Rules Here -------------------*/
   IF (nRtagId IS NULL)
   THEN
      RAISE_APPLICATION_ERROR (-20000, 'Missing some parameters! nRtagId= '|| nRtagId  );
   END IF;


   -- Check if other release references this release
   SELECT COUNT( rl.RTAG_ID ) INTO RecCount
     FROM RELEASE_LINKS rl
    WHERE rl.REF_RTAG_ID = nRtagId;

   IF (RecCount > 0) THEN
      RAISE_APPLICATION_ERROR (-20000, 'This release is referenced by other release and cannot be destroyed.'  );
   END IF;
   /*-------------------------------------------------------*/

   -- Delete Release links
   DELETE
     FROM RELEASE_LINKS rl
    WHERE rl.RTAG_ID = nRtagId;

   -- Delete ignore warning
   DELETE
     FROM IGNORE_WARNINGS iw
    WHERE iw.RTAG_ID = nRtagId;


   -- Delete Build Order cached calculations
   DELETE
     FROM BUILD_ORDER bo
    WHERE bo.RTAG_ID = nRtagId;


   -- Delete Notification History
   DELETE
     FROM NOTIFICATION_HISTORY nh
    WHERE nh.RTAG_ID = nRtagId;


   -- Delete Released Area Contents
   DELETE
     FROM RELEASE_CONTENT rc
    WHERE rc.RTAG_ID = nRtagId;


   -- Delete Work In Progress Area Contents
   DELETE
     FROM WORK_IN_PROGRESS wip
    WHERE wip.RTAG_ID = nRtagId;


   -- Delete Pending Area Contents
   DELETE
     FROM PLANNED pl
    WHERE pl.RTAG_ID = nRtagId;

   -- Delete Deprecated Packages
   DELETE
     FROM DEPRECATED_PACKAGES dp
    WHERE dp.RTAG_ID = nRtagId;

   -- Delete Project Action Log
   DELETE
     FROM PROJECT_ACTION_LOG pal
    WHERE pal.RTAG_ID = nRtagId;

   -- Delete Do Not Ripple Contents
   DELETE
     FROM DO_NOT_RIPPLE dnr
    WHERE dnr.RTAG_ID = nRtagId;

   -- Delete Dash Board Contents
   DELETE
     FROM DASH_BOARD db
    WHERE db.RTAG_ID = nRtagId;

   -- Delete Advisory Ripple Contents
   DELETE
     FROM ADVISORY_RIPPLE adr
    WHERE adr.RTAG_ID = nRtagId;

   -- Delete Archive Action Log
   DELETE
     FROM ARCHIVE_ACTION_LOG aal
    WHERE aal.RTAG_ID = nRtagId;

   -- Delete Daemons For This Release
   FOR rcon IN (SELECT rc.RCON_ID FROM RELEASE_CONFIG rc WHERE rc.RTAG_ID = nRtagId )
   LOOP
      rconIdList := rconIdList || rcon.RCON_ID || ',';
   END LOOP;

   pk_buildapi.DELETE_DAEMON(rconIdList);

   -- Delete Release Metrics Contents
   DELETE
     FROM RELEASE_METRICS rm
    WHERE rm.RTAG_ID = nRtagId;

   -- Delete Release Configuration Contents
   DELETE
     FROM RELEASE_CONFIG rc
    WHERE rc.RTAG_ID = nRtagId;

   -- Delete Pegged Version Contents
   DELETE
     FROM PEGGED_VERSIONS pegv
    WHERE pegv.RTAG_ID = nRtagId;

END;
/*-------------------------------------------------------------------------------------------------------*/
FUNCTION GET_PARENT_RTAG ( nRtagId IN NUMBER, nSourceRtagId IN NUMBER, cIsBranch IN CHAR )  RETURN NUMBER IS

   nSourceParentRtagId NUMBER;

BEGIN
   /*--------------- Business Rules Here -------------------*/
   IF (nRtagId IS NULL) OR (cIsBranch IS NULL)
   THEN
      RAISE_APPLICATION_ERROR (-20000, 'Missing some parameters! nRtagId= '|| nRtagId ||', cIsBranch= '|| cIsBranch );
   END IF;
   /*-------------------------------------------------------*/


   IF ( nSourceRtagId IS NULL ) THEN
      -- Create new on main branch
      RETURN nRtagId;

   ELSE
      -- Create from source rtag_id

      -- Find parent of Source RtagId
      SELECT rt.PARENT_RTAG_ID INTO nSourceParentRtagId
        FROM RELEASE_TAGS rt
       WHERE rt.RTAG_ID = nSourceRtagId;

      IF (UPPER(cIsBranch) = 'Y') THEN
         RETURN nSourceRtagId;
      ELSE
         IF (nSourceRtagId = nSourceParentRtagId) THEN
            RETURN nRtagId;
         ELSE
            RETURN nSourceParentRtagId;
         END IF;
      END IF;


   END IF;


END;
/*-------------------------------------------------------------------------------------------------------*/

-- PROCEDURE Get_Next_Version ( nSourceRtagId IN NUMBER,
--                       sNextVersion OUT VARCHAR2,
--                       nNextLifeCycle OUT NUMBER,
--                       nParentRtagId OUT NUMBER,
--                       nProjId IN NUMBER ) IS
--
-- SourceBranchCount NUMBER;
-- ProjRootVersion VARCHAR2(4000);
-- LastLifeCycle NUMBER;
-- ROOT_VERSION_NOT_FOUND NUMBER := -1;
-- SET_PARENT_AS_YOURSELF NUMBER := -1;
--
-- SourceProjId NUMBER;
-- SourceVersion RELEASE_TAGS.RTAG_VERSION%TYPE;
-- SourceLifeCycle RELEASE_TAGS.RTAG_LIFE_CYCLE%TYPE;
--
-- BEGIN
--    /*--------------- Business Rules Here -------------------*/
--    /*-------------------------------------------------------*/
--
--
--    BEGIN
--       -- Get Project root version
--       SELECT rt.RTAG_VERSION INTO ProjRootVersion
--         FROM RELEASE_TAGS rt
--        WHERE rt.PROJ_ID = nProjId
--          AND rt.RTAG_ID = rt.PARENT_RTAG_ID;
--
--       EXCEPTION
--       WHEN NO_DATA_FOUND THEN
--       ProjRootVersion := ROOT_VERSION_NOT_FOUND;
--    END;
--
--
--
--
--    BEGIN
--       -- Get info for source rtagid
--       SELECT rt.PROJ_ID, rt.RTAG_VERSION, rt.RTAG_LIFE_CYCLE  INTO  SourceProjId, SourceVersion, SourceLifeCycle
--         FROM RELEASE_TAGS rt
--        WHERE rt.RTAG_ID = nSourceRtagId;
--
--       EXCEPTION
--       WHEN NO_DATA_FOUND THEN
--       SourceProjId := NULL;
--       SourceVersion := NULL;
--       SourceLifeCycle := NULL;
--    END;
--
--
--    IF (nSourceRtagId IS NULL)  OR  ( SourceProjId != nProjId ) THEN
--
--       /* Blank Release Required  OR  Release imported from other project */
--
--       IF (ProjRootVersion = ROOT_VERSION_NOT_FOUND) THEN
--          /* No Releases found in the project, hence calculate next version available.  */
--
--          -- Set parent rtag
--          nParentRtagId := SET_PARENT_AS_YOURSELF;
--
--
--          BEGIN
--             -- Get Next Available Global Root Version
--             SELECT MAX( TO_NUMBER( rt.RTAG_VERSION ) )  INTO  ProjRootVersion
--               FROM RELEASE_TAGS rt
--              WHERE rt.RTAG_ID = rt.PARENT_RTAG_ID;
--
--             -- Set Next Rtag Version
--             sNextVersion := CAST( ProjRootVersion + 1 AS VARCHAR2 );
--
--             -- Restart Lifecycle
--             nNextLifeCycle := 0;
--
--
--             EXCEPTION
--             WHEN NO_DATA_FOUND THEN
--             -- Release Manager has no releases, hence start from 1
--             sNextVersion := '1';
--             nNextLifeCycle := 0;
--
--          END;
--
--
--
--       ELSE
--          /* Releases found in this project. */
--
--          SELECT qry.RTAG_ID, qry.RTAG_LIFE_CYCLE  INTO nParentRtagId, LastLifeCycle
--            FROM (
--                SELECT rt.RTAG_ID, rt.RTAG_LIFE_CYCLE
--                  FROM RELEASE_TAGS rt
--                 WHERE rt.PROJ_ID = nProjId
--                   AND rt.RTAG_VERSION = ProjRootVersion
--                 ORDER BY rt.RTAG_LIFE_CYCLE DESC
--                  ) qry
--           WHERE ROWNUM = 1;
--
--
--          -- Set same Rtag Version
--          sNextVersion := ProjRootVersion;
--
--          -- Increase Lifecycle
--          nNextLifeCycle := LastLifeCycle + 1;
--
--       END IF;
--
--
--
--    ELSE
--       /* Create Release From other release within this project */
--
--       -- Set parent id
--       nParentRtagId := nSourceRtagId;
--
--
--       -- Get number of source branches
--       SELECT COUNT(rt.RTAG_ID) INTO SourceBranchCount
--         FROM RELEASE_TAGS rt
--        WHERE rt.PROJ_ID = nProjId
--          AND rt.PARENT_RTAG_ID = nSourceRtagId;
--
--
--       IF SourceBranchCount = 0 THEN
--          /* Release is Head (i.e. Tip on its branch ) */
--
--          -- Set Next Rtag Version
--          sNextVersion := SourceVersion;
--
--          -- Increase Lifecycle
--          nNextLifeCycle := SourceLifeCycle + 1;
--
--
--       ELSIF SourceBranchCount = 1 THEN
--          /* Release IS NOT Head, but can be branched */
--
--          -- Set Next Rtag Version
--          sNextVersion := SourceVersion ||'.'|| SourceLifeCycle;
--
--          -- Reset Lifecycle to 1
--          nNextLifeCycle := 1;
--
--
--       ELSE
--          -- Limit of two branches is reached
--          RAISE_APPLICATION_ERROR (-20000, 'This release is already branched and cannot be branched again. ');
--
--       END IF;
--
--
--
--
--
--
--    END IF;
--
--
-- END;

/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE GET_VIEW_CONTENT ( RtagId IN NUMBER, ViewId IN NUMBER, RecordSet OUT typeCur ) as 
begin
OPEN RecordSet FOR
-- Determine the PV_ID and OPERATION for the required VIEW
With selectedPv as (
    SELECT pv.pv_id, ' ' as operation, 0 as pkg_state
      FROM RELEASE_CONTENT rel, package_versions pv, VIEW_DEF vd,  VIEWS vi
      WHERE rel.pv_id = pv.pv_id
      AND vd.PKG_ID = pv.PKG_ID
      AND vd.VIEW_ID = ViewId
      AND rel.RTAG_ID = RtagId
      AND vi.VIEW_ID = ViewId
      AND vi.BASE_VIEW NOT IN ('Y', 'S')
    UNION
     SELECT rel.pv_id, ' ' as operation, 0 as pkg_state
     FROM RELEASE_CONTENT rel, VIEWS vi
     WHERE rel.BASE_VIEW_ID = ViewId
     AND rel.RTAG_ID = RtagId
     AND vi.VIEW_ID = ViewId
     AND vi.BASE_VIEW IN ('Y', 'S')
),
-- Determine packages that are building
building as (
    SELECT unique rl.CURRENT_PV_ID as pv_id, rc.RTAG_ID 
    FROM RELEASE_CONFIG rc, RELEASE_TAGS rt, RUN_LEVEL rl 
    WHERE rt.RTAG_ID = rc.RTAG_ID
    AND rc.RTAG_ID = RtagId
    AND rc.bmcon_id is not null
    AND rt.OFFICIAL in ( 'N', 'R', 'C')
    AND rl.RCON_ID(+) = rc.RCON_ID
    AND rl.CURRENT_PKG_ID_BEING_BUILT is not null
    AND NVL(rl.PAUSE,0) < 2
), 
-- Determine Packages that are scheduled to build    
scheduled as (
    SELECT pv_id, RTAG_ID from daemon_instructions di
    WHERE di.op_code = 2
    AND RTAG_ID = RtagId
) , 
-- Determine Packages that failed to build or have been excluded
buildFail as (
    SELECT pv_id, root_pv_id, RTAG_ID from do_not_ripple dnr
    WHERE RTAG_ID = RtagId
) 
-- Generate the complete dataset from the fragments
  SELECT Case
                    When sdi.pv_id is not null then 14
                    When bb.pv_id is not null then 15
                    When bf.pv_id is not null AND bf.root_pv_id is NULL then 16
                    When bf.pv_id is not null AND bf.root_pv_id is NOT NULL then  17
                    When rel.pkg_state is not null then rel.pkg_state
                    Else 0
                End as pkg_state,
               NULL AS DEPRECATED_STATE,
               pv.pv_id,
               pkg.pkg_name,
               pv.pkg_version,
               pv.dlocked,
               pv.pv_description,
               pv.BUILD_TYPE,
               rel.operation
          FROM selectedPv rel,
               packages pkg,
               package_versions pv,
               scheduled sdi,
               buildFail bf,
               building bb
         WHERE pv.pkg_id = pkg.pkg_id
           AND rel.pv_id = pv.pv_id
           AND sdi.pv_id(+) = rel.pv_id
           AND bf.pv_id(+) = rel.pv_id
           AND bb.pv_id(+) = rel.pv_id
         ORDER BY UPPER(pkg.PKG_NAME), pv.pv_id;
END;

/*-------------------------------------------------------------------------------------------------------*/
  -- Add or Replace a package to the specified release
PROCEDURE ADD_PACKAGE ( newPvId IN NUMBER, ViewId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER ) IS
   ReleaseLocation VARCHAR2(4000);
   nPkgId NUMBER;
   sVExt VARCHAR2(4000);
   IsPatch PACKAGE_VERSIONS.IS_PATCH%TYPE := 'N';
   default_pegged CHAR := 'N';
   default_advisory_ripple CHAR := 'N';

   -- Find package for replacement
   CURSOR curReplacePkg IS
    SELECT pv.PV_ID
     FROM RELEASE_CONTENT rc,
           PACKAGE_VERSIONS pv
    WHERE rc.PV_ID = pv.PV_ID
      AND rc.RTAG_ID = RtagId
      AND pv.PKG_ID = nPkgId
      AND NVL( pv.V_EXT, 'LINK_A_NULL' ) = NVL( sVExt, 'LINK_A_NULL' );
    recReplacePkg curReplacePkg%ROWTYPE;

BEGIN
   -- Get is_patch, pkg_id and v_ext
   SELECT pv.IS_PATCH, pv.PKG_ID, pv.V_EXT
     INTO IsPatch, nPkgId, sVExt
     FROM PACKAGE_VERSIONS pv
    WHERE pv.PV_ID = newPvId;

   -- Never put patch in relesed area
   IF (IsPatch != 'Y') OR (IsPatch IS NULL) THEN

      -- Try to get a package to be replaced with this new one.
      -- Use unique constraint of PKG_ID and V_EXT
      OPEN curReplacePkg;
       FETCH curReplacePkg INTO recReplacePkg;

       IF curReplacePkg%FOUND THEN
         -- Replace package
         REPLACE_PACKAGE ( newPvId, recReplacePkg.PV_ID, RtagId, UserId );

      ELSE
         -- Add new package
         INSERT INTO RELEASE_CONTENT ( RTAG_ID, PV_ID, BASE_VIEW_ID, INSERT_STAMP, INSERTOR_ID, PKG_STATE )
         VALUES( RtagId, newPvId, ViewId, ora_sysdatetime, UserId, 0);

        -- Insert default package flags
        -- Get Package Level defaults

        SELECT pkg.default_pegged, pkg.DEFAULT_ADVISORY_RIPPLE
         INTO  default_pegged, default_advisory_ripple
         FROM  PACKAGES pkg
        WHERE  pkg.PKG_ID = nPkgId;

        -- Apply to the newly inserted package
        IF default_pegged = 'Y' THEN
          INSERT INTO PEGGED_VERSIONS ( RTAG_ID, PV_ID ) VALUES (RtagId, newPvId);
          -- Log_Action ( newPvId, 'action', UserId, 'Set default package peg' );
        END IF;

        IF default_advisory_ripple = 'Y' THEN
          INSERT INTO ADVISORY_RIPPLE ( RTAG_ID, PV_ID ) VALUES (RtagId, newPvId);
          -- Log_Action ( newPvId, 'action', UserId, 'Set default advisory ripple' );
        END IF;

        -- Mark Release as changed
        SET_RELEASE_MODIFIED(RtagId);
        RUN_POST_ACTIONS(newPvId, RtagId);

          /* LOG ACTION */
         SELECT proj.PROJ_NAME ||' / '|| rt.RTAG_NAME INTO ReleaseLocation
           FROM PROJECTS proj,
                 RELEASE_TAGS rt
          WHERE rt.PROJ_ID = proj.PROJ_ID
            AND rt.RTAG_ID = RtagId;

         Log_Action ( newPvId, 'add', UserId, 'Location: '|| ReleaseLocation );

      END IF;
      CLOSE curReplacePkg;
   END IF;
END;

/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE REPLACE_PACKAGE ( newPvId IN NUMBER, oldPvId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER ) IS

   ReleaseLocation VARCHAR2(4000);
   sPkgVersion VARCHAR2(4000);
   nSdkTag NUMBER;
   cPersistRippleStop CHAR;
   cRippleStop CHAR;
BEGIN
   -- Extract essential information
      SELECT SDKTAG_ID, PERSIST_RIPPLE_STOP INTO nSdkTag, cPersistRippleStop FROM RELEASE_CONTENT
      WHERE rtag_id = RtagId
       AND pv_id = oldPvId;

   -- Trap SDK Replacement
   -- This is a last ditch check. The application should not allow this condition to happen
     If nSdkTag IS NOT NULL  THEN
       raise_application_error (-20000, 'Attempt to replace a package provided by an SDK.');
     END IF;

   -- Determine new value for ripple_stop
   cRippleStop := NULL;
   IF cPersistRippleStop is NOT NULL THEN
      cRippleStop := 's';
   END IF;

   -- Replace Package
    UPDATE RELEASE_CONTENT
       SET pv_id = newPvId,
           insert_stamp = ora_sysdatetime,
           insertor_id = UserId,
           product_state = NULL,
           ripple_stop = cRippleStop
     WHERE rtag_id = RtagId
       AND pv_id = oldPvId;

   -- update the pegging table
   UPDATE PEGGED_VERSIONS
      SET pv_id = newPvId
     WHERE rtag_id = RtagId
       AND pv_id = oldPvId;

   -- update the advisory_ripple table
   UPDATE ADVISORY_RIPPLE
      SET pv_id = newPvId
     WHERE rtag_id = RtagId
       AND pv_id = oldPvId;

    /* LOG ACTION */
   SELECT proj.PROJ_NAME ||' / '|| rt.RTAG_NAME INTO ReleaseLocation
     FROM PROJECTS proj,
           RELEASE_TAGS rt
    WHERE rt.PROJ_ID = proj.PROJ_ID
      AND rt.RTAG_ID = RtagId;

   SELECT pv.PKG_VERSION INTO sPkgVersion
     FROM PACKAGE_VERSIONS pv
    WHERE pv.PV_ID = newPvId;

   SET_RELEASE_MODIFIED(RtagId);
   Log_Action ( oldPvId, 'replaced_with', UserId, 'Replacing with: '|| sPkgVersion ||' at '|| ReleaseLocation );
   Log_Action ( newPvId, 'add', UserId, 'Location: '|| ReleaseLocation );

END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE REMOVE_PACKAGE ( PvId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER ) IS
   ReleaseLocation VARCHAR2(4000);
   nSdkTag NUMBER;
BEGIN
   -- Trap SDK Package Deletion
   -- This is a last ditch check. The application should not allow this condition to happen
      SELECT SDKTAG_ID INTO nSdkTag FROM RELEASE_CONTENT
      WHERE rtag_id = RtagId
       AND pv_id = PvId;

     If nSdkTag IS NOT NULL  THEN
       raise_application_error (-20000, 'Attempt to delete a package provided by an SDK.');
     END IF;

   -- Delete old package
   DELETE
     FROM RELEASE_CONTENT rc
    WHERE rc.PV_ID = PvId
      AND rc.RTAG_ID = RtagId;


   /* LOG ACTION */
   SELECT proj.PROJ_NAME ||' / '|| rt.RTAG_NAME INTO ReleaseLocation
     FROM PROJECTS proj,
          RELEASE_TAGS rt
    WHERE rt.PROJ_ID = proj.PROJ_ID
      AND rt.RTAG_ID = RtagId;

   Log_Action ( PvId, 'delete_from_released', UserId, 'Location: '|| ReleaseLocation );


END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE REMOVE_MATCHING_PACKAGE ( PvId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER ) IS
   ReleaseLocation VARCHAR2(4000);

   CURSOR curMatchingPackage IS
    SELECT mpv.PV_ID
     FROM RELEASE_CONTENT rc,
           PACKAGE_VERSIONS mpv,
         PACKAGE_VERSIONS pv
    WHERE rc.PV_ID = mpv.PV_ID
      AND rc.RTAG_ID = RtagId
      AND pv.PV_ID = PvId
      AND pv.PKG_ID = mpv.PKG_ID
      AND NVL( pv.V_EXT, '|LINK_A_NULL|' ) = NVL( mpv.V_EXT, '|LINK_A_NULL|' );
    recMatchingPackage curMatchingPackage%ROWTYPE;

BEGIN

   OPEN curMatchingPackage;
    FETCH curMatchingPackage INTO recMatchingPackage;

    IF curMatchingPackage%FOUND THEN
      -- Delete old package
      DELETE
        FROM RELEASE_CONTENT rc
       WHERE rc.PV_ID = recMatchingPackage.PV_ID
         AND rc.RTAG_ID = RtagId;


      /* LOG ACTION */
      SELECT proj.PROJ_NAME ||' / '|| rt.RTAG_NAME INTO ReleaseLocation
        FROM PROJECTS proj,
              RELEASE_TAGS rt
       WHERE rt.PROJ_ID = proj.PROJ_ID
         AND rt.RTAG_ID = RtagId;

      Log_Action ( recMatchingPackage.PV_ID, 'delete_from_released', UserId, 'Location: '|| ReleaseLocation );

   END IF;


   CLOSE curMatchingPackage;




END;
/*-------------------------------------------------------------------------------------------------------*/
FUNCTION GET_PACKAGE_VIEW ( PvId IN NUMBER, RtagId IN NUMBER ) RETURN NUMBER IS

   ReturnValue NUMBER;

BEGIN
   SELECT rc.BASE_VIEW_ID INTO ReturnValue
     FROM RELEASE_CONTENT rc
    WHERE rc.RTAG_ID = RtagId
      AND rc.PV_ID = PvId;

   RETURN ReturnValue;
END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE RUN_POST_ACTIONS ( PvId IN NUMBER, RtagId IN NUMBER ) IS

BEGIN
   -- Reset Ignore warnings up-the-tree
   RESET_IGNORE_WARNINGS ( TO_CHAR(PvId), RtagId );

   -- Refresh Package states
   TOUCH_RELEASE ( RtagId );

END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE RUN_POST_ACTIONS_BULK ( PvId IN NUMBER ) IS
   CURSOR curReleases IS
    SELECT rc.RTAG_ID
     FROM RELEASE_CONTENT rc
    WHERE rc.PV_ID = PvId;
    recReleases curReleases%ROWTYPE;

BEGIN

   OPEN curReleases;
    FETCH curReleases INTO recReleases;

   WHILE curReleases%FOUND
   LOOP

      RUN_POST_ACTIONS ( PvId, recReleases.RTAG_ID );

      FETCH curReleases INTO recReleases;
   END LOOP;

   CLOSE curReleases;

END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE CHANGE_PACKAGE_VIEW ( PvId IN NUMBER, RtagId IN NUMBER, NewViewId IN NUMBER ) IS

BEGIN

   UPDATE RELEASE_CONTENT rc SET
   rc.BASE_VIEW_ID = NewViewId
   WHERE rc.PV_ID = PvId
     AND rc.RTAG_ID = RtagId;

END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE ADD_RELEASE_REFERENCE ( nRtagId IN NUMBER, nRefRtagId IN NUMBER, ProblemString OUT VARCHAR2 ) IS

   RowCount NUMBER;


   CURSOR curPackageClash IS
   SELECT pkg.PKG_NAME,
         er.*
     FROM (

           /* Get existing referenced packages */
         SELECT pv.PKG_ID,
                pv.V_EXT
           FROM RELEASE_LINKS rl,
                 RELEASE_CONTENT rc,
                 PACKAGE_VERSIONS pv
          WHERE rl.RTAG_ID = nRtagId
            AND rl.REF_RTAG_ID = rc.RTAG_ID
            AND rc.PV_ID = pv.PV_ID

            ) er,
         (

         /* Get current reference packages */
         SELECT pv.PKG_ID,
                pv.V_EXT
           FROM RELEASE_CONTENT rc,
                 PACKAGE_VERSIONS pv
          WHERE rc.RTAG_ID = nRefRtagId
            AND rc.PV_ID = pv.PV_ID

         ) cr,
         PACKAGES PKG
    WHERE er.PKG_ID = cr.PKG_ID
      AND NVL(er.V_EXT, '|LINK_A_NULL|') = NVL(cr.V_EXT, '|LINK_A_NULL|')
      AND er.PKG_ID = pkg.PKG_ID;

   recPackageClash curPackageClash%ROWTYPE;

BEGIN
   /*--------------- Business Rules Here -------------------*/
   IF (nRtagId = 0) OR ( nRtagId IS NULL ) THEN
      RAISE_APPLICATION_ERROR (-20000, 'nRtagId is not supplied. [nRtagId='|| nRtagId ||']' );
   END IF;

   IF (nRefRtagId = 0) OR ( nRefRtagId IS NULL ) THEN
      RAISE_APPLICATION_ERROR (-20000, 'nRefRtagId is not supplied. [nRefRtagId='|| nRefRtagId ||']' );
   END IF;
   /*-------------------------------------------------------*/
   ProblemString := NULL;


   -- Check if release already has references
   SELECT COUNT(rl.RTAG_ID)  INTO  RowCount
     FROM RELEASE_LINKS rl
    WHERE rl.RTAG_ID = nRtagId;


   IF RowCount > 0 THEN
      -- Found existing references

      -- Make sure there is no package clashes
      OPEN curPackageClash;
       FETCH curPackageClash INTO recPackageClash;

      IF curPackageClash%FOUND THEN

         ProblemString := ProblemString ||'Following is partial list of package already referenced from other release:'|| PK_PACKAGE.CRLF;

         WHILE curPackageClash%FOUND
         LOOP
            EXIT WHEN LENGTH( ProblemString || '- '|| recPackageClash.PKG_NAME ||' '|| recPackageClash.V_EXT  || PK_PACKAGE.CRLF ) > 200;   -- Do not allow variable overflow

            ProblemString := ProblemString || '- '|| recPackageClash.PKG_NAME ||' '|| recPackageClash.V_EXT  || PK_PACKAGE.CRLF;

            FETCH curPackageClash INTO recPackageClash;
         END LOOP;

      END IF;

      CLOSE curPackageClash;


   ELSE
      -- No references found, hence reference a release


      -- Remove exising package from this release to be referenced
      REMOVE_RELEASE_REFERENCE ( nRtagId, nRefRtagId);


      -- Add new linked packages to release
      INSERT INTO RELEASE_CONTENT rc (RTAG_ID, PV_ID, BASE_VIEW_ID, INSERT_STAMP, INSERTOR_ID, PKG_STATE)
      SELECT nRtagId,
            rc.PV_ID,
            rc.BASE_VIEW_ID,
            rc.INSERT_STAMP,
            rc.INSERTOR_ID,
            rc.PKG_STATE
        FROM RELEASE_CONTENT rc
       WHERE rc.RTAG_ID = nRefRtagId;



      -- Copy ignore warnings for referenced packages
      INSERT INTO IGNORE_WARNINGS iw (RTAG_ID, PV_ID, DPV_ID, IS_PATCH_IGNORE)
      SELECT nRtagId,
            iw.PV_ID,
            iw.DPV_ID,
            iw.IS_PATCH_IGNORE
        FROM IGNORE_WARNINGS iw,
              RELEASE_CONTENT rc
       WHERE iw.RTAG_ID = rc.RTAG_ID
         AND iw.PV_ID = rc.PV_ID
         AND rc.RTAG_ID = nRefRtagId;



      -- Reference release
      INSERT INTO RELEASE_LINKS (RTAG_ID, REF_RTAG_ID)
      VALUES ( nRtagId, nRefRtagId );


      -- Refresh Package states
      TOUCH_RELEASE ( nRtagId );

   END IF;


END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE REMOVE_RELEASE_REFERENCE ( nRtagId IN NUMBER, nRefRtagId IN NUMBER ) IS


BEGIN
   /*--------------- Business Rules Here -------------------*/
   IF (nRtagId = 0) OR ( nRtagId IS NULL ) THEN
      RAISE_APPLICATION_ERROR (-20000, 'nRtagId is not supplied. [nRtagId='|| nRtagId ||']' );
   END IF;

   IF (nRefRtagId = 0) OR ( nRefRtagId IS NULL ) THEN
      RAISE_APPLICATION_ERROR (-20000, 'nRefRtagId is not supplied. [nRefRtagId='|| nRefRtagId ||']' );
   END IF;

   /*-------------------------------------------------------*/


   -- Remove ignore warnings for those packages who use referenced packages
   DELETE FROM IGNORE_WARNINGS iw
    WHERE iw.RTAG_ID = nRtagId
      AND iw.DPV_ID IN (
                        SELECT dep.DPV_ID
                       FROM (

                           /* Get referenced packages */
                           SELECT pv.PKG_ID,
                                  pv.V_EXT
                             FROM RELEASE_CONTENT rc,
                                   PACKAGE_VERSIONS pv
                            WHERE rc.RTAG_ID = nRefRtagId
                              AND rc.PV_ID = pv.PV_ID

                           ) cr,
                           (

                           /* Get all dependencies for current release */
                           SELECT DISTINCT
                                 pv.PKG_ID,
                                 pv.V_EXT,
                                 dep.DPV_ID
                             FROM RELEASE_CONTENT rc,
                                 PACKAGE_DEPENDENCIES dep,
                                 PACKAGE_VERSIONS pv
                            WHERE rc.RTAG_ID = nRtagId
                              AND rc.PV_ID = dep.PV_ID
                              AND dep.PV_ID = pv.PV_ID

                           ) dep
                      WHERE dep.PKG_ID = cr.PKG_ID
                        AND NVL(dep.V_EXT, '|LINK_A_NULL|') = NVL(cr.V_EXT, '|LINK_A_NULL|')
                     );




   -- Remove ignore warnings for those package which are going to be replaced with the reference
   DELETE FROM IGNORE_WARNINGS iw
    WHERE iw.RTAG_ID = nRtagId
      AND iw.PV_ID IN (
                  SELECT pv.PV_ID
                    FROM (

                        /* Get referenced packages */
                        SELECT pv.PKG_ID,
                               pv.V_EXT
                          FROM RELEASE_CONTENT rc,
                                PACKAGE_VERSIONS pv
                         WHERE rc.RTAG_ID = nRefRtagId
                           AND rc.PV_ID = pv.PV_ID

                        ) cr,
                        RELEASE_CONTENT rc,
                        PACKAGE_VERSIONS pv
                   WHERE pv.PKG_ID = cr.PKG_ID
                     AND NVL(pv.V_EXT, '|LINK_A_NULL|') = NVL(cr.V_EXT, '|LINK_A_NULL|')
                     AND rc.RTAG_ID = nRtagId
                     AND rc.PV_ID = pv.PV_ID
                  );





   -- Remove matching packages from release
   DELETE FROM RELEASE_CONTENT rc
    WHERE rc.RTAG_ID = nRtagId
      AND rc.PV_ID IN (
                  SELECT pv.PV_ID
                    FROM (

                        /* Get referenced packages */
                        SELECT pv.PKG_ID,
                               pv.V_EXT
                          FROM RELEASE_CONTENT rc,
                                PACKAGE_VERSIONS pv
                         WHERE rc.RTAG_ID = nRefRtagId
                           AND rc.PV_ID = pv.PV_ID

                        ) cr,
                        RELEASE_CONTENT rc,
                        PACKAGE_VERSIONS pv
                   WHERE pv.PKG_ID = cr.PKG_ID
                     AND NVL(pv.V_EXT, '|LINK_A_NULL|') = NVL(cr.V_EXT, '|LINK_A_NULL|')
                     AND rc.RTAG_ID = nRtagId
                     AND rc.PV_ID = pv.PV_ID
                  );





   -- Remove Reference release
   DELETE
     FROM RELEASE_LINKS rl
    WHERE rl.RTAG_ID = nRtagId
      AND rl.REF_RTAG_ID = nRefRtagId;


   -- Refresh Package states
   TOUCH_RELEASE ( nRtagId );


END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE CAN_USER_WRITE_TO_RELEASE ( RtagId IN NUMBER, PvId IN NUMBER, Permission IN CHAR ) IS

   cReleaseMode CHAR(1);
   cPvMode CHAR(1);

BEGIN

   -- Get Release Mode
   SELECT rt.OFFICIAL INTO cReleaseMode
     FROM RELEASE_TAGS rt
    WHERE rt.RTAG_ID = RtagId;


   -- Get Package Mode
   SELECT pv.DLOCKED INTO cPvMode
     FROM PACKAGE_VERSIONS pv
    WHERE pv.PV_ID = PvId;

   -- Only check if package is locked
   IF (cPvMode = 'Y') THEN

      IF (cReleaseMode != 'N') AND (Permission != 'Y')
      THEN
         RAISE_APPLICATION_ERROR (-20000, 'Cannot add package to this release. Release needs to be in Open Mode.' );

      END IF;

   END IF;
END;

/*-----------------------------------------------------------------------------*/
PROCEDURE SET_RELEASE_MODIFIED (nRtagId IN NUMBER ) IS
--
--  Set flags to indicate that the specified release has changed for the
--  purposes of building. (Not every single change)
--
--  Used by Build System to streamline build decisions
--    Bump a sequence number
--    Set a TimeStamp
--
--  Care must be taken to avoid concuency issues
--  Must Insert or Update in a safe manner
--
--  This should be called whenever the package_versions in the release have changed in such
--  a manner that the build daemons should examine the release. This includes:
--   - Packages added, removed and version updated
--   - Packages build status changed (re-included in the release)
--   - Packages made Pending Build
--   - Daemon instruction add/updated (Test Build)
--
--  Note: Not yet used (10-Oct-2014)
--        Uses SEQ_RELEASE_MOD and Table: RELEASE_MODIFIED
BEGIN
 LOOP
  BEGIN
    MERGE INTO RELEASE_MODIFIED USING dual ON ( RTAG_ID=nRtagId )
      WHEN MATCHED THEN UPDATE SET SEQNUM=SEQ_RELEASE_MOD.NEXTVAL,TIMESTAMP=CURRENT_TIMESTAMP
      WHEN NOT MATCHED THEN INSERT (RTAG_ID,TIMESTAMP,SEQNUM)
        VALUES (nRtagId, CURRENT_TIMESTAMP,SEQ_RELEASE_MOD.NEXTVAL );
    EXIT; -- success? -> exit loop
  EXCEPTION
    WHEN NO_DATA_FOUND THEN -- the entry was concurrently deleted
      NULL; -- exception? -> no op, i.e. continue looping
    WHEN DUP_VAL_ON_INDEX THEN -- an entry was concurrently inserted
      NULL; -- exception? -> no op, i.e. continue looping
  END;
 END LOOP;
END;

/*-------------------------------------------------------------------------------------------------------*/
--  ADD_RELEASE_SDK
--  ADD an SDK Reference to a Release
--  Args: nRtagId           - RTAG_ID of Release to Process
--        nSdktagId         - SDKTAG_ID of SDK to add to Release
--        nUserId           - User IF of user performing the action
--        bDelete           - Delete conflicting (non sdk) packages from the release 0:False
--        nInsertCount      - Returns: Number of Packages inserted: -1 is an error
--        curReturn         - Returns: On error a table of PV_IDs of packages causing the conflict
--
PROCEDURE ADD_RELEASE_SDK ( nRtagId IN NUMBER, nSdktagId IN NUMBER, nUserId IN NUMBER, bDelete IN NUMBER, nInsertCount OUT NUMBER, curReturn OUT typeCur )IS

  vartbl RELMGR_NUMBER_TAB_T := RELMGR_NUMBER_TAB_T();
  ii NUMBER;
  view_id NUMBER;

    -- Detect clashing packages
    -- Packages provided by the SDK that are present in the Release
    CURSOR curPackageClash
    IS
      SELECT release.pvid
      FROM
        -- Alias and pvid from SDK
        (SELECT pv.PKG_ID || NVL(pv.V_EXT, '.NULL') AS pkgAlias,
          pv.PV_ID                  AS pvid
        FROM SDK_CONTENT sc, PACKAGE_VERSIONS pv
        WHERE sc.SDKTAG_ID  = nSdktagId
        AND sc.SDKPKG_STATE = 'E'
        AND pv.PV_ID        = sc.PV_ID
        ) sdk,
      -- Alias and pvid from Release
      (SELECT pv.PKG_ID || NVL(pv.V_EXT, '.NULL') AS pkgAlias,
        pv.PV_ID                  AS pvid
      FROM RELEASE_CONTENT rc, PACKAGE_VERSIONS pv
      WHERE rc.rtag_id = nRtagId
      AND rc.PV_ID    = pv.PV_ID
      ) RELEASE
    WHERE sdk.pkgAlias = release.pkgAlias;

   -- Detect packages in the release that are provided by the SDK
   -- Do not include packages provided by an SDK - these cannot be replaced
       CURSOR curPackageReplacable
    IS
      SELECT release.pvid
      FROM
        -- Alias and pvid from SDK
        (SELECT pv.PKG_ID || NVL(pv.V_EXT, '.NULL') AS pkgAlias,
                pv.PV_ID                            AS pvid
        FROM SDK_CONTENT sc, PACKAGE_VERSIONS pv
        WHERE sc.SDKTAG_ID    = nSdktagId
          AND sc.SDKPKG_STATE = 'E'
          AND pv.PV_ID        = sc.PV_ID
        ) sdk,
      -- Alias and pvid from Release
      --  Excluding those import by any SDK
      (SELECT pv.PKG_ID || NVL(pv.V_EXT, '.NULL') AS pkgAlias,
              pv.PV_ID                            AS pvid
       FROM RELEASE_CONTENT rc, PACKAGE_VERSIONS pv
       WHERE rc.rtag_id = nRtagId
         AND rc.PV_ID   = pv.PV_ID
         AND rc.SDKTAG_ID is NULL
      ) RELEASE
    WHERE sdk.pkgAlias = release.pkgAlias;

BEGIN
   /*--------------- Business Rules Here -------------------*/
   IF (nRtagId = 0) OR ( nRtagId IS NULL ) THEN
      RAISE_APPLICATION_ERROR (-20000, 'nRtagId is not supplied. [nRtagId='|| nRtagId ||']' );
   END IF;

   IF (nSdktagId = 0) OR ( nSdktagId IS NULL ) THEN
      RAISE_APPLICATION_ERROR (-20000, 'nSdktagId is not supplied. [nSdktagId='|| nSdktagId ||']' );
   END IF;
   /*-------------------------------------------------------*/

   -- Delete packages from the release if they are provided by the SDK
   -- provided they are not provided by another SDK
    IF bDelete != 0 THEN
      FOR rdata IN curPackageClash LOOP
        DELETE FROM RELEASE_CONTENT rc
          WHERE rc.RTAG_ID = nRtagId
          AND rc.PV_ID = rdata.pvid;
      END LOOP;

      -- Remove exising package from this release to be referenced
      REMOVE_RELEASE_SDK ( nRtagId, nSdktagId);
    END IF;

    -- Detect and report package clashes
    -- Packages provided by the SDK that are (still) in the release
    ii := 1;
    FOR rdata IN curPackageClash LOOP
      vartbl.extend;
      --vartbl(ii) := TABLE_PVID(rdata.pvid);
      vartbl(ii) := rdata.pvid;
      ii := ii + 1;
    END LOOP;
    -- Make sure there is no package clashes

    IF ii != 1 THEN
      nInsertCount := -1;
      open curReturn for select * from table(vartbl);
      --curReturn := vartbl;
      RETURN;
    END IF;

    -- Determine the target view_id
    SELECT sn.VIEW_ID into view_id FROM SDK_TAGS st,  SDK_NAMES sn WHERE sn.SDK_ID = st.SDK_ID AND st.SDKTAG_ID = nSdktagId;

    -- Add SDK exported packages to release
    INSERT INTO RELEASE_CONTENT rc (RTAG_ID, PV_ID, BASE_VIEW_ID, INSERT_STAMP, INSERTOR_ID, PKG_STATE, SDKTAG_ID)
    SELECT nRtagId, sc.PV_ID, view_id, sysdate, nUserId, 11, nSdktagId
        FROM SDK_CONTENT sc
        WHERE sc.SDKTAG_ID = nSdktagId
        AND sc.SDKPKG_STATE = 'E';
    nInsertCount := sql%ROWCOUNT;

    -- Refresh Package states
    TOUCH_RELEASE ( nRtagId );
    SET_RELEASE_MODIFIED(nRtagId);

END;

/*-------------------------------------------------------------------------------------------------------*/
--  Name:   REMOVE_RELEASE_SDK
--  Desc:   Remove an SDK from the specified Release
--          It is not an error to remove an SDK that is not attached to the release
--  Args:   nRtagId         - RTAG_ID of the Release to Process
--          nSdktagId       - SDKTAG_ID to remove
--
PROCEDURE REMOVE_RELEASE_SDK ( nRtagId IN NUMBER, nSdktagId IN NUMBER ) IS

BEGIN
   /*--------------- Business Rules Here -------------------*/
   IF (nRtagId = 0) OR ( nRtagId IS NULL ) THEN
      RAISE_APPLICATION_ERROR (-20000, 'nRtagId is not supplied. [nRtagId='|| nRtagId ||']' );
   END IF;

   IF (nSdktagId = 0) OR ( nSdktagId IS NULL ) THEN
      RAISE_APPLICATION_ERROR (-20000, 'nSdktagId is not supplied. [nSdktagId='|| nSdktagId ||']' );
   END IF;

   /*-------------------------------------------------------*/

   -- Remove matching packages from release
   DELETE FROM RELEASE_CONTENT rc
    WHERE rc.RTAG_ID = nRtagId
      AND rc.SDKTAG_ID = nSdktagId;

   -- Refresh Package states
   TOUCH_RELEASE ( nRtagId );
   SET_RELEASE_MODIFIED(nRtagId);
END;

--------------------------------------------------------------------------------
--  CAN_ADD_PKG_TO_RELEASE
--  Test if a Package (pvid) can be added to a given release
--  The test will not allwo an exiting package to be replaced IF it is imported via an
--  SDK
--
--  Returns:  0 - Package cannot be replaced
--            1 - Package can be replaced
--            2 - Package will be added
--
FUNCTION CAN_ADD_PKG_TO_RELEASE ( nRtagId IN NUMBER, nPvid in NUMBER ) RETURN NUMBER IS

   sAlias VARCHAR2(4000);

    -- Find package for proccessing
    -- Use unique constraint of PKG_ID and V_EXT
   CURSOR curReplacePkg IS
    SELECT pv.PV_ID
     FROM RELEASE_CONTENT rc,
           PACKAGE_VERSIONS pv
    WHERE rc.PV_ID = pv.PV_ID
      AND rc.RTAG_ID = nRtagId
      AND pv.PKG_ID || NVL( pv.V_EXT, 'LINK_A_NULL' ) = sAlias;

    recReplacePkg curReplacePkg%ROWTYPE;
    nSdkTag NUMBER;

BEGIN
   /*--------------- Business Rules Here -------------------*/
   IF (nRtagId = 0) OR ( nRtagId IS NULL ) THEN
      RAISE_APPLICATION_ERROR (-20000, 'nRtagId is not supplied. [nRtagId='|| nRtagId ||']' );
   END IF;

   IF (nPvid = 0) OR ( nPvid IS NULL ) THEN
      RAISE_APPLICATION_ERROR (-20000, 'nPvid is not supplied. [nPvid='|| nPvid ||']' );
   END IF;

    -- Find pkg Alias for provided package
   SELECT pv.PKG_ID || NVL( pv.V_EXT, 'LINK_A_NULL' )
     INTO sAlias
     FROM PACKAGE_VERSIONS pv
    WHERE pv.PV_ID = nPvid;

      -- Find Package that may be replaced
      OPEN curReplacePkg;
       FETCH curReplacePkg INTO recReplacePkg;

       IF curReplacePkg%FOUND THEN
        SELECT SDKTAG_ID INTO nSdkTag FROM RELEASE_CONTENT
         WHERE rtag_id = nRtagId
         AND pv_id = recReplacePkg.PV_ID;

        If nSdkTag IS NOT NULL  THEN
          RETURN 0;
        ELSE
          RETURN 1;
        END IF;
      END IF;

  -- No package found, so it can be added
  RETURN 2;

  EXCEPTION
  WHEN NO_DATA_FOUND THEN
    RAISE_APPLICATION_ERROR (-20000, 'nPvid is not valid. [nPvid='|| nPvid ||']' );
END;

/*-------------------------------------------------------------------------------------------------------*/
END PK_RELEASE;

/
--------------------------------------------------------
--  DDL for Package Body PK_RMAPI
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE BODY "RELEASE_MANAGER"."PK_RMAPI" 
IS

   /*-------------------------------------------------------------------------------------------------------*/
   FUNCTION package_dependencies (pkgname VARCHAR2, pkgversion VARCHAR2)
      RETURN typecur
   IS
      npvid     NUMBER  := 0;
      RECORDS   typecur;
   BEGIN
      BEGIN
         -- Get PV_ID --
         SELECT pv.pv_id
           INTO npvid
           FROM PACKAGES pkg, package_versions pv
          WHERE pv.pkg_id = pkg.pkg_id
            AND pkg.pkg_name = pkgname
            AND pv.pkg_version = pkgversion;
      EXCEPTION
         WHEN NO_DATA_FOUND
         THEN
            raise_application_error (-20000, 'Package Not Found!');
            --WHEN OTHERS THEN
                  -- Consider logging the error and then re-raise
            RAISE;
      END;

      -- Finally get package dependencies --
      OPEN RECORDS FOR
         SELECT dpv.pv_id, dpkg.pkg_name, dpv.pkg_version
           FROM package_dependencies dep, PACKAGES dpkg, package_versions dpv
          WHERE dep.pv_id = npvid
            AND dpv.pkg_id = dpkg.pkg_id
            AND dpv.pv_id = dep.dpv_id;

      RETURN RECORDS;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   FUNCTION wip_iteration_package (
      projname        VARCHAR2,
      iterationname   VARCHAR2,
      pkgname         VARCHAR2
   )
      RETURN typecur
   IS
      nrtagid   NUMBER  := 0;
      RECORDS   typecur;
   BEGIN
      BEGIN
         -- Get latest rtag_id --
         SELECT rt.rtag_id
           INTO nrtagid
           FROM projects proj, release_tags rt
          WHERE rt.proj_id = proj.proj_id
            AND UPPER (proj.proj_name) = UPPER (projname)
            AND UPPER (rt.rtag_name) = UPPER (iterationname);

         IF (nrtagid IS NULL)
         THEN
            raise_application_error (-20000,
                                     'Work In Progress is Not Found!');
         END IF;
      EXCEPTION
         WHEN NO_DATA_FOUND
         THEN
            raise_application_error (-20000,
                                     'Work In Progress is Not Found!');
            RAISE;
      END;

      -- Finally get package dependencies --
      OPEN RECORDS FOR
         SELECT pv.pkg_version, pv.dlocked AS is_official, pv.pkg_label,
                pv.src_path
           FROM PACKAGES pkg, package_versions pv, work_in_progress wip
          WHERE pv.pkg_id = pkg.pkg_id
            AND wip.pv_id = pv.pv_id
            AND wip.rtag_id = nrtagid
            AND pkg.pkg_name = pkgname;

      RETURN RECORDS;
   END;

/*-------------------------------------------------------------------------------------------------------*/
-- Use:
--   Used by the Automated Build System to release a new package
-- Returns:
--    Use application errors to indicate programming errors
--    Use negative return codes to indicate correctable user problems
--    Positive return code is the new PVID of the package
--
-- Note: Being deprecated in favor of auto_make_vcsrelease2
  FUNCTION auto_make_vcsrelease (
      rtagid                   IN   NUMBER,
      pkgname                  IN   VARCHAR2,
      vext                     IN   VARCHAR2,
      newpkgversion            IN   VARCHAR2,
      vcstag                   IN   VARCHAR2,
      dependenciesimportlist   IN   VARCHAR2,
      isrippled                IN   NUMBER,
      username                 IN   VARCHAR2
   )
      RETURN NUMBER
   IS
      pkgid                           NUMBER;
      pvid                            NUMBER                        := 0;
      userid                          NUMBER;
      dlocked                         VARCHAR2 (20)                 := NULL;
      clonefrompvid                   NUMBER;
      ssv_mm                          package_versions.v_mm%TYPE;
      ssv_nmm                         package_versions.v_nmm%TYPE;
      ssv_ext                         package_versions.v_ext%TYPE;
      return_package_not_found        NUMBER                        := -1;
      return_package_already_exists   NUMBER                        := -2;
      return_not_approved             NUMBER                        := -3;
      return_migrated_pkg             NUMBER                        := -4;
      return_svn_path_changed         NUMBER                        := -5;


      x_vcstypeid                     NUMBER;
      x_tag                           VARCHAR2(32);
      x_label                         VARCHAR2(60);
      x_srcpath                       VARCHAR2(2000);
      p_srcpath                       VARCHAR2(2000);

      -- Regular expression constituents
      Token         VARCHAR2(16) := '([^:]+)';  -- a token is anything except a ':' character
      Seperator     VARCHAR2(4)  := '::';       -- tokens will be seperated by '::'
      BOL           VARCHAR2(4)  := '^';
      Anything      VARCHAR2(4)  := '.*';
      ReplaceToken1 VARCHAR2(4)  := '\1';
      ReplaceToken2 VARCHAR2(4)  := '\2';
      ReplaceToken3 VARCHAR2(4)  := '\3';
      iprev_modifier_id               NUMBER;

   BEGIN
      /*--------------- Business Rules Here -------------------*/
      IF (rtagid IS NULL)
      THEN
         raise_application_error (-20000, 'RtagId must be supplied.');
      END IF;

      IF (pkgname IS NULL)
      THEN
         raise_application_error (-20000, 'PkgName must be supplied.');
      END IF;

      IF (newpkgversion IS NULL)
      THEN
         raise_application_error (-20000, 'PkgVersion must be supplied.');
      END IF;

      IF (vcstag IS NULL)
      THEN
         raise_application_error (-20000, 'PkgVcsTag must be supplied.');
      END IF;

      IF (isrippled IS NULL) OR (isrippled < 0) OR (isrippled > 1)
      THEN
         raise_application_error (-20000, 'IsRippled must be set to 1 (Is rippled build) or 0 (Is planned build).');
      END IF;

      IF (username IS NULL)
      THEN
         raise_application_error (-20000, 'UserName must be supplied.');
      END IF;

      -- Parse the PkgVcsTag
      -- Sets up
      --   x_tag, x_label, x_srcpath

       BEGIN
          -- Extract the first token - this will be the short tag name for the VCS (eg. 'CC', 'SVN', etc)
          x_tag := REGEXP_REPLACE(vcstag, BOL || Token || Seperator || Anything, ReplaceToken1);

          -- Decode the short tag
          CASE x_tag
             WHEN 'CC' THEN
                -- extract the 2nd and 3rd tokens, those being the source path and label respectively
                x_srcpath := REGEXP_REPLACE(vcstag, BOL || Token || Seperator || Token || Seperator || Anything, ReplaceToken2);
                x_label   := REGEXP_REPLACE(vcstag, BOL || Token || Seperator || Token || Seperator || Token, ReplaceToken3);

                -- NOTE: if reg-expr parsing/replacement fails, the x_... variable may receive the entire input string (vcstag), so
                -- check for that error as well as the obvious zero-length string conditions.
                IF LENGTH(x_srcpath) = 0 OR LENGTH(x_label) = 0 OR x_srcpath = vcstag OR x_label = vcstag THEN
                   raise_application_error (-20000, 'VCS Tag contains insufficient or malformed data!');
                END IF;

                IF isSVNbyName(pkgname) > 0 THEN
                    -- Don't allow migrated packages to be released from a CC label
                    return return_migrated_pkg;
                END IF;


             WHEN 'SVN' THEN
                -- extract the 2nd token, that being the subversion tag
                x_srcpath := REGEXP_REPLACE(vcstag, BOL || Token || Seperator || Token || Seperator || Anything, ReplaceToken2);
                x_label   := REGEXP_REPLACE(vcstag, BOL || Token || Seperator || Token || Seperator || Token, ReplaceToken3);

                -- NOTE: if reg-expr parsing/replacement fails, the x_... variable may receive the entire input string (vcstag), so
                -- check for that error as well as the obvious zero-length string conditions.
                IF LENGTH(x_srcpath) = 0 OR LENGTH(x_label) = 0 OR x_srcpath = vcstag OR x_label = vcstag THEN
                   raise_application_error (-20000, 'VCS Tag contains insufficient or malformed data!');
                END IF;

             WHEN 'UC' THEN
                -- nothing to extract, just assign defaults
                x_srcpath := REGEXP_REPLACE(vcstag, BOL || Token || Seperator || Token || Seperator || Anything, ReplaceToken2);
                x_label   := 'N/A';
             ELSE
                raise_application_error (-20000, 'Unrecognised VCS Tag!');
          END CASE;
       END;

      -- Get the VCS_TYPE_ID for the version control system.
      BEGIN
         SELECT vt.vcs_type_id
         INTO x_vcstypeid
         FROM VCS_TYPE vt
         WHERE vt.tag = x_tag;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               raise_application_error (-20000, 'Database is missing a version control system tag (' || x_tag || ')!' );
      END;


      -- Get user_id
      BEGIN
         SELECT usr.user_id
           INTO userid
           FROM users usr
          WHERE UPPER (usr.user_name) = UPPER (username)
            AND usr.is_disabled IS NULL;
      EXCEPTION
         WHEN NO_DATA_FOUND
         THEN
            raise_application_error (-20000, 'UserName: ' || username || ' is not valid or disabled.' );
      END;

/*-------------------------------------------------------*/

      -- Create package if necessary
      IF isrippled = 1
      THEN
         /* Ripple Build */
         BEGIN
            -- Make sure that package does not exist
            SELECT pv.pv_id
              INTO pvid
              FROM package_versions pv, PACKAGES pkg
             WHERE pv.pkg_id = pkg.pkg_id
               AND pkg.pkg_name = pkgname
               AND pv.pkg_version = newpkgversion;
         EXCEPTION
            WHEN NO_DATA_FOUND
            THEN
               pvid := 0;
         END;

         IF (pvid = 0)
         THEN
            -- Split current version in parts
            split_version (newpkgversion, ssv_mm, ssv_nmm, ssv_ext);

            BEGIN
               -- Find package to be replaced with the ripple package
               IF NVL (vext, '|LINK_A_NULL|') = NVL (ssv_ext, '|LINK_A_NULL|')
               THEN
                  SELECT pv.pv_id, pv.src_path
                    INTO clonefrompvid, p_srcpath
                    FROM PACKAGES pkg, package_versions pv,
                         release_content rc
                   WHERE rc.pv_id = pv.pv_id
                     AND pv.pkg_id = pkg.pkg_id
                     AND rc.rtag_id = rtagid
                     AND pkg.pkg_name = pkgname
                     AND NVL (pv.v_ext, '|LINK_A_NULL|') = NVL (ssv_ext, '|LINK_A_NULL|');
               ELSE
                  SELECT pv.pv_id, pv.src_path
                    INTO clonefrompvid, p_srcpath
                    FROM PACKAGES pkg, package_versions pv,
                         release_content rc
                   WHERE rc.pv_id = pv.pv_id
                     AND pv.pkg_id = pkg.pkg_id
                     AND rc.rtag_id = rtagid
                     AND pkg.pkg_name = pkgname
                     AND NVL (pv.v_ext, '|LINK_A_NULL|') = NVL (vext, '|LINK_A_NULL|');
               END IF;
            EXCEPTION
               WHEN NO_DATA_FOUND
               THEN
                  raise_application_error
                                        (-20000,
                                            'Cannot get CloneFromPvId. VExt='
                                         || vext
                                         || ', RtagId='
                                         || rtagid
                                         || ', PkgName='
                                         || pkgname
                                         || ', SSV_EXT='
                                         || ssv_ext
                                        );
            END;

            IF NVL (vext, '|LINK_A_NULL|') = NVL (ssv_ext, '|LINK_A_NULL|')
            THEN
               -- Create package
               seed_package_names_versions (pkgname,
                                            newpkgversion,
                                            userid,
                                            pvid,
                                            clonefrompvid
                                           );
            ELSE
               -- Create package (now both the same)
               seed_package_names_versions (pkgname,
                                             newpkgversion,
                                             userid,
                                             pvid,
                                             clonefrompvid
                                            );
            END IF;

            -- Update Package reason for release
            UPDATE package_versions pv
               SET pv.comments = 'Rippled Build.',
                   pv.build_type = 'Y'
             WHERE pv.pv_id = pvid;
         ELSE
            -- Package already exists, it was built previously, and has just been re-built again probably due to the
            -- fact that the archive was cleaned of the original build artifacts at some point, and those artifacts
            -- are now needed once more. As such, we need to ensure that a new release note generation occurs so
            -- reset the package_versions[pvid].release_notes_info field to enable that to happen.
            UPDATE package_versions pv
               SET pv.release_notes_info = null,
                   pv.modified_stamp = ora_sysdatetime
             WHERE pv.pv_id = pvid;

            --DEVI-066151
            log_action (pvid, 'package_rebuilt', userid, 'Package Re-built...');

            RETURN return_package_already_exists;
         END IF;
      ELSE
         /* Auto build from Pending area */

         -- Find package in pending area
         BEGIN
            SELECT pv.pv_id, pv.dlocked, pv.src_path
              INTO pvid, dlocked, p_srcpath
              FROM planned pl, package_versions pv, PACKAGES pkg
             WHERE pl.pv_id = pv.pv_id
               AND pv.pkg_id = pkg.pkg_id
               AND pl.rtag_id = rtagid
               AND pkg.pkg_name = pkgname
               AND pv.dlocked = 'A'
               AND NVL (pv.v_ext, '|LINK_A_NULL|') = NVL (vext, '|LINK_A_NULL|')
               AND rownum = 1
             ORDER BY pv.modified_stamp;
         EXCEPTION
            WHEN NO_DATA_FOUND
            THEN
               pvid := 0;
         END;

         IF (pvid = 0)
         THEN
            -- Package does not exist in pending area, hence report it
            RETURN return_package_not_found;
         ELSIF (dlocked != 'A')
         THEN
            -- Package is not approved for autobuild
            RETURN return_not_approved;
         END IF;

      END IF;

      -- Ensure Source Path does not change
      -- Do not expect the SVN development branch to change
      -- From the previous package
      IF ( x_tag = 'SVN' AND p_srcpath != x_srcpath )
      THEN
        return return_svn_path_changed;
      END IF;

      BEGIN
         -- Import Dependencies
         import_dependencies (pvid, dependenciesimportlist, userid);
      END;


      BEGIN
         -- Split current version in parts
         split_version (newpkgversion, ssv_mm, ssv_nmm, ssv_ext);

         -- Update Package Details
         UPDATE package_versions pv
            SET pv.pkg_version = newpkgversion,
                pv.v_ext = ssv_ext,
                pv.v_mm = ssv_mm,
                pv.v_nmm = ssv_nmm,
                pv.src_path = x_srcpath,
                pv.pkg_label = x_label,
                pv.vcs_type_id = x_vcstypeid
          WHERE pv.pv_id = pvid;
      EXCEPTION
         WHEN DUP_VAL_ON_INDEX
         THEN
            -- Package already exists, hence cannot be used for ripple build
            RETURN return_package_already_exists;
      END;

      -- Update the is_autobuildable
      UPDATE package_versions
         SET is_autobuildable = 'Y'
       WHERE pv_id = pvid;

      -- DEVI-063601
      -- For planned builds the modifier_id shouldn't be set to buildadm.
      -- To ensure this the modifier_id is obtained so it can be restored after
      -- the function pk_environment.auto_make_release is called.
      -- This function calls, change_state, which sets the modifier_id to the
      -- specified userid, which for auto builds is buildadm.
      SELECT pv.modifier_id INTO iprev_modifier_id
      FROM package_versions pv WHERE pv.pv_id = pvid;

      -- Now release package
      pk_environment.auto_make_release (pvid,
                                        rtagid,
                                        userid,
                                        vext,
                                        ssv_ext,
                                        clonefrompvid
                                       );

      -- DEVI-063601
      -- if it is a planned build then restore the modifier_id to the previous modifier
      UPDATE package_versions pv SET pv.modifier_id = iprev_modifier_id
      WHERE pv.pv_id = pvid;

      --Now clean the PLANNED_VERSIONS table
      SELECT pkg_id
        INTO pkgid
        FROM PACKAGES
       WHERE pkg_name = pkgname;

      DELETE FROM planned_versions
            WHERE pkg_id = pkgid AND pkg_version = newpkgversion;

      RETURN pvid;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE import_dependencies (
      pvid                     IN   NUMBER,
      dependenciesimportlist   IN   VARCHAR2,
      userid                   IN   NUMBER
   )
   IS
/*
|| DependenciesImportList Format:
|| "pkgA","1.0.0";"pkgB","2.0.0";
||  OR 'pkgA','1.0.0';'pkgB','2.0.0';
*/
      TYPE tdictionary IS TABLE OF VARCHAR2 (4000)
         INDEX BY VARCHAR2 (4000);

      seperator         VARCHAR2 (2)           := '||';
      pkgname           VARCHAR2 (4000);
      pkgversion        VARCHAR2 (4000);
      buildtype         VARCHAR2 (50);
      pkgid             NUMBER;
      vext              VARCHAR2 (4000);
      dpvid             NUMBER;
      slist             VARCHAR2 (4000);
      cbuildtypes       tdictionary;
      dependencyrow     NUMBER;
      sdependency       VARCHAR2 (4000);
      first_pos         VARCHAR2 (4000);
      second_pos        VARCHAR2 (4000);
      third_pos         VARCHAR2 (4000);
      forth_pos         VARCHAR2 (4000);
      citemcollection   relmgr_varchar2_tab_t  := relmgr_varchar2_tab_t ();

      CURSOR curbuildtype
      IS
         SELECT dpv.pkg_id || seperator || dpv.v_ext AS pkgid_ext,
                dep.build_type
           FROM package_dependencies dep, package_versions dpv
          WHERE dep.pv_id = pvid AND dep.dpv_id = dpv.pv_id;

      recbuildtype      curbuildtype%ROWTYPE;
   BEGIN
      slist := dependenciesimportlist;

      -- Preformat String
      IF NOT slist IS NULL
      THEN
         slist := REPLACE (slist, ' ');                      -- Remove spaces
         slist := REPLACE (slist, UTL_TCP.crlf);
         -- Remove new line and carriage-return characters
         slist := REPLACE (slist, '''', '"');             -- Replace ' with "
      END IF;

      -- Get Current Dependencies
      OPEN curbuildtype;

      FETCH curbuildtype
       INTO recbuildtype;

      WHILE curbuildtype%FOUND
      LOOP
         cbuildtypes (recbuildtype.pkgid_ext) := recbuildtype.build_type;

         FETCH curbuildtype
          INTO recbuildtype;
      END LOOP;

      CLOSE curbuildtype;

      -- Separate dependencies with ; separator
      citemcollection := in_list_varchar2 (slist, ';');

      BEGIN
         -- Remove old dependencies
         DELETE FROM package_dependencies dep
               WHERE dep.pv_id = pvid;

         -- Loop through dependencies
         FOR dependencyrow IN 1 .. citemcollection.COUNT
         LOOP
            -- Extract pkg_name and pkg_version
            sdependency := citemcollection (dependencyrow);
            first_pos := INSTR (sdependency, '"', 1, 1);
            second_pos := INSTR (sdependency, '"', 1, 2);
            third_pos := INSTR (sdependency, '"', 1, 3);
            forth_pos := INSTR (sdependency, '"', 1, 4);
            pkgname :=
               SUBSTR (sdependency,
                       (first_pos + 1),
                       (second_pos - first_pos - 1)
                      );
            pkgversion :=
               SUBSTR (sdependency,
                       (third_pos + 1),
                       (forth_pos - third_pos - 1)
                      );

            -- Dependency must exits to be linked against
            BEGIN
               SELECT pv.pv_id, pv.pkg_id, pv.v_ext
                 INTO dpvid, pkgid, vext
                 FROM package_versions pv, PACKAGES pkg
                WHERE pv.pkg_id = pkg.pkg_id
                  AND pkg.pkg_name = pkgname
                  AND pv.pkg_version = pkgversion;
            EXCEPTION
               WHEN NO_DATA_FOUND
               THEN
                  raise_application_error
                                  (-20000,
                                      'Dependency ['
                                   || pkgname
                                   || ' '
                                   || pkgversion
                                   || '] does not exist yet and cannot be used!'
                                  );
            END;

            -- Get Build Type (i.e. BuildPackageArchive or LinkPackageArchive)
            BEGIN
               buildtype := cbuildtypes (pkgid || seperator || vext);

               IF buildtype IS NULL
               THEN
                  -- Set build type to LinkPackageArchive by default
                  buildtype := 'L';
               END IF;
            EXCEPTION
               WHEN NO_DATA_FOUND
               THEN
                  buildtype := 'L';
            END;

            -- Insert Dependencies
            update_package_dependency (pvid,
                                       pkgname,
                                       pkgversion,
                                       buildtype,
                                       userid,
                                       0
                                      );
         END LOOP;
      END;
   END;

/*-------------------------------------------------------------------------------------------------------*/
-- Use:
--   Used by the Automated Build System to release a new package
-- Returns:
--    Use application errors to indicate programming errors
--    Use negative return codes to indicate correctable user problems
--    Positive return code is the new PVID of the package
  FUNCTION auto_make_vcsrelease2 (
      rtagid                   IN   NUMBER,
      pkgname                  IN   VARCHAR2,
      vext                     IN   VARCHAR2,
      newpkgversion            IN   VARCHAR2,
      vcstag                   IN   VARCHAR2,
      dependenciesimportlist   IN   relmgr_varchar2_tab_t,
      isrippled                IN   NUMBER,
      username                 IN   VARCHAR2
   )
      RETURN NUMBER
   IS
      pkgid                           NUMBER;
      pvid                            NUMBER                        := 0;
      userid                          NUMBER;
      dlocked                         VARCHAR2 (20)                 := NULL;
      clonefrompvid                   NUMBER;
      ssv_mm                          package_versions.v_mm%TYPE;
      ssv_nmm                         package_versions.v_nmm%TYPE;
      ssv_ext                         package_versions.v_ext%TYPE;
      return_package_not_found        NUMBER                        := -1;
      return_package_already_exists   NUMBER                        := -2;
      return_not_approved             NUMBER                        := -3;
      return_migrated_pkg             NUMBER                        := -4;
      return_svn_path_changed         NUMBER                        := -5;


      x_vcstypeid                     NUMBER;
      x_tag                           VARCHAR2(32);
      x_label                         VARCHAR2(60);
      x_srcpath                       VARCHAR2(2000);
      p_srcpath                       VARCHAR2(2000);

      -- Regular expression constituents
      Token         VARCHAR2(16) := '([^:]+)';  -- a token is anything except a ':' character
      Seperator     VARCHAR2(4)  := '::';       -- tokens will be seperated by '::'
      BOL           VARCHAR2(4)  := '^';
      Anything      VARCHAR2(4)  := '.*';
      ReplaceToken1 VARCHAR2(4)  := '\1';
      ReplaceToken2 VARCHAR2(4)  := '\2';
      ReplaceToken3 VARCHAR2(4)  := '\3';
      iprev_modifier_id               NUMBER;

   BEGIN
      /*--------------- Business Rules Here -------------------*/
      IF (rtagid IS NULL)
      THEN
         raise_application_error (-20000, 'RtagId must be supplied.');
      END IF;

      IF (pkgname IS NULL)
      THEN
         raise_application_error (-20000, 'PkgName must be supplied.');
      END IF;

      IF (newpkgversion IS NULL)
      THEN
         raise_application_error (-20000, 'PkgVersion must be supplied.');
      END IF;

      IF (vcstag IS NULL)
      THEN
         raise_application_error (-20000, 'PkgVcsTag must be supplied.');
      END IF;

      IF (isrippled IS NULL) OR (isrippled < 0) OR (isrippled > 1)
      THEN
         raise_application_error (-20000, 'IsRippled must be set to 1 (Is rippled build) or 0 (Is planned build).');
      END IF;

      IF (username IS NULL)
      THEN
         raise_application_error (-20000, 'UserName must be supplied.');
      END IF;

      -- Parse the PkgVcsTag
      -- Sets up
      --   x_tag, x_label, x_srcpath

       BEGIN
          -- Extract the first token - this will be the short tag name for the VCS (eg. 'CC', 'SVN', etc)
          x_tag := REGEXP_REPLACE(vcstag, BOL || Token || Seperator || Anything, ReplaceToken1);

          -- Decode the short tag
          CASE x_tag
             WHEN 'CC' THEN
                -- extract the 2nd and 3rd tokens, those being the source path and label respectively
                x_srcpath := REGEXP_REPLACE(vcstag, BOL || Token || Seperator || Token || Seperator || Anything, ReplaceToken2);
                x_label   := REGEXP_REPLACE(vcstag, BOL || Token || Seperator || Token || Seperator || Token, ReplaceToken3);

                -- NOTE: if reg-expr parsing/replacement fails, the x_... variable may receive the entire input string (vcstag), so
                -- check for that error as well as the obvious zero-length string conditions.
                IF LENGTH(x_srcpath) = 0 OR LENGTH(x_label) = 0 OR x_srcpath = vcstag OR x_label = vcstag THEN
                   raise_application_error (-20000, 'VCS Tag contains insufficient or malformed data!');
                END IF;

                IF isSVNbyName(pkgname) > 0 THEN
                    -- Don't allow migrated packages to be released from a CC label
                    return return_migrated_pkg;
                END IF;


             WHEN 'SVN' THEN
                -- extract the 2nd token, that being the subversion tag
                x_srcpath := REGEXP_REPLACE(vcstag, BOL || Token || Seperator || Token || Seperator || Anything, ReplaceToken2);
                x_label   := REGEXP_REPLACE(vcstag, BOL || Token || Seperator || Token || Seperator || Token, ReplaceToken3);

                -- NOTE: if reg-expr parsing/replacement fails, the x_... variable may receive the entire input string (vcstag), so
                -- check for that error as well as the obvious zero-length string conditions.
                IF LENGTH(x_srcpath) = 0 OR LENGTH(x_label) = 0 OR x_srcpath = vcstag OR x_label = vcstag THEN
                   raise_application_error (-20000, 'VCS Tag contains insufficient or malformed data!');
                END IF;

             WHEN 'UC' THEN
                -- nothing to extract, just assign defaults
                x_srcpath := REGEXP_REPLACE(vcstag, BOL || Token || Seperator || Token || Seperator || Anything, ReplaceToken2);
                x_label   := 'N/A';
             ELSE
                raise_application_error (-20000, 'Unrecognised VCS Tag!');
          END CASE;
       END;

      -- Get the VCS_TYPE_ID for the version control system.
      BEGIN
         SELECT vt.vcs_type_id
         INTO x_vcstypeid
         FROM VCS_TYPE vt
         WHERE vt.tag = x_tag;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               raise_application_error (-20000, 'Database is missing a version control system tag (' || x_tag || ')!' );
      END;


      -- Get user_id
      BEGIN
         SELECT usr.user_id
           INTO userid
           FROM users usr
          WHERE UPPER (usr.user_name) = UPPER (username)
            AND usr.is_disabled IS NULL;
      EXCEPTION
         WHEN NO_DATA_FOUND
         THEN
            raise_application_error (-20000, 'UserName: ' || username || ' is not valid or disabled.' );
      END;

/*-------------------------------------------------------*/

      -- Create package if necessary
      IF isrippled = 1
      THEN
         /* Ripple Build */
         BEGIN
            -- Make sure that package does not exist
            SELECT pv.pv_id
              INTO pvid
              FROM package_versions pv, PACKAGES pkg
             WHERE pv.pkg_id = pkg.pkg_id
               AND pkg.pkg_name = pkgname
               AND pv.pkg_version = newpkgversion;
         EXCEPTION
            WHEN NO_DATA_FOUND
            THEN
               pvid := 0;
         END;

         IF (pvid = 0)
         THEN
            -- Split current version in parts
            split_version (newpkgversion, ssv_mm, ssv_nmm, ssv_ext);

            BEGIN
               -- Find package to be replaced with the ripple package
               IF NVL (vext, '|LINK_A_NULL|') = NVL (ssv_ext, '|LINK_A_NULL|')
               THEN
                  SELECT pv.pv_id, pv.src_path
                    INTO clonefrompvid, p_srcpath
                    FROM PACKAGES pkg, package_versions pv,
                         release_content rc
                   WHERE rc.pv_id = pv.pv_id
                     AND pv.pkg_id = pkg.pkg_id
                     AND rc.rtag_id = rtagid
                     AND pkg.pkg_name = pkgname
                     AND NVL (pv.v_ext, '|LINK_A_NULL|') = NVL (ssv_ext, '|LINK_A_NULL|');
               ELSE
                  SELECT pv.pv_id, pv.src_path
                    INTO clonefrompvid, p_srcpath
                    FROM PACKAGES pkg, package_versions pv,
                         release_content rc
                   WHERE rc.pv_id = pv.pv_id
                     AND pv.pkg_id = pkg.pkg_id
                     AND rc.rtag_id = rtagid
                     AND pkg.pkg_name = pkgname
                     AND NVL (pv.v_ext, '|LINK_A_NULL|') = NVL (vext, '|LINK_A_NULL|');
               END IF;
            EXCEPTION
               WHEN NO_DATA_FOUND
               THEN
                  raise_application_error
                                        (-20000,
                                            'Cannot get CloneFromPvId. VExt='
                                         || vext
                                         || ', RtagId='
                                         || rtagid
                                         || ', PkgName='
                                         || pkgname
                                         || ', SSV_EXT='
                                         || ssv_ext
                                        );
            END;

            IF NVL (vext, '|LINK_A_NULL|') = NVL (ssv_ext, '|LINK_A_NULL|')
            THEN
               -- Create package
               seed_package_names_versions (pkgname,
                                            newpkgversion,
                                            userid,
                                            pvid,
                                            clonefrompvid
                                           );
            ELSE
               -- Create package (now both the same)
               seed_package_names_versions (pkgname,
                                             newpkgversion,
                                             userid,
                                             pvid,
                                             clonefrompvid
                                            );
            END IF;

            -- Update Package reason for release
            UPDATE package_versions pv
               SET pv.comments = 'Rippled Build.',
                   pv.build_type = 'Y'
             WHERE pv.pv_id = pvid;
         ELSE
            -- Package already exists, it was built previously, and has just been re-built again probably due to the
            -- fact that the archive was cleaned of the original build artifacts at some point, and those artifacts
            -- are now needed once more. As such, we need to ensure that a new release note generation occurs so
            -- reset the package_versions[pvid].release_notes_info field to enable that to happen.
            UPDATE package_versions pv
               SET pv.release_notes_info = null,
                   pv.modified_stamp = ora_sysdatetime
             WHERE pv.pv_id = pvid;

            --DEVI-066151
            log_action (pvid, 'package_rebuilt', userid, 'Package Re-built...');

            RETURN return_package_already_exists;
         END IF;
      ELSE
         /* Auto build from Pending area */

         -- Find package in pending area
         BEGIN
            SELECT pv.pv_id, pv.dlocked, pv.src_path
              INTO pvid, dlocked, p_srcpath
              FROM planned pl, package_versions pv, PACKAGES pkg
             WHERE pl.pv_id = pv.pv_id
               AND pv.pkg_id = pkg.pkg_id
               AND pl.rtag_id = rtagid
               AND pkg.pkg_name = pkgname
               AND pv.dlocked = 'A'
               AND NVL (pv.v_ext, '|LINK_A_NULL|') = NVL (vext, '|LINK_A_NULL|')
               AND rownum = 1
             ORDER BY pv.modified_stamp;
         EXCEPTION
            WHEN NO_DATA_FOUND
            THEN
               pvid := 0;
         END;

         IF (pvid = 0)
         THEN
            -- Package does not exist in pending area, hence report it
            RETURN return_package_not_found;
         ELSIF (dlocked != 'A')
         THEN
            -- Package is not approved for autobuild
            RETURN return_not_approved;
         END IF;

      END IF;

      -- Ensure Source Path does not change
      -- Do not expect the SVN development branch to change
      -- From the previous package
      IF ( x_tag = 'SVN' AND p_srcpath != x_srcpath )
      THEN
        return return_svn_path_changed;
      END IF;

      BEGIN
         -- Import Dependencies
         import_dependencies2 (pvid, dependenciesimportlist, userid);
      END;


      BEGIN
         -- Split current version in parts
         split_version (newpkgversion, ssv_mm, ssv_nmm, ssv_ext);

         -- Update Package Details
         UPDATE package_versions pv
            SET pv.pkg_version = newpkgversion,
                pv.v_ext = ssv_ext,
                pv.v_mm = ssv_mm,
                pv.v_nmm = ssv_nmm,
                pv.src_path = x_srcpath,
                pv.pkg_label = x_label,
                pv.vcs_type_id = x_vcstypeid
          WHERE pv.pv_id = pvid;
      EXCEPTION
         WHEN DUP_VAL_ON_INDEX
         THEN
            -- Package already exists, hence cannot be used for ripple build
            RETURN return_package_already_exists;
      END;

      -- The package has been auto built, for the first time

      -- DEVI-063601
      -- For planned builds the modifier_id shouldn't be set to buildadm.
      -- To ensure this the modifier_id is obtained so it can be restored after
      -- the function pk_environment.auto_make_release is called.
      -- This function calls, change_state, which sets the modifier_id to the
      -- specified userid, which for auto builds is buildadm.
      SELECT pv.modifier_id INTO iprev_modifier_id
      FROM package_versions pv WHERE pv.pv_id = pvid;

      -- Now release package
      pk_environment.auto_make_release (pvid,
                                        rtagid,
                                        userid,
                                        vext,
                                        ssv_ext,
                                        clonefrompvid
                                       );

      -- DEVI-063601 if it is a planned build then restore the modifier_id to the previous modifier
      -- Set the package as autobuildable ( auto built )
      -- Update the created timestamp to the current date-time. When it was first released
      UPDATE package_versions pv SET 
        pv.modifier_id = iprev_modifier_id,
        is_autobuildable = 'Y',
        pv.created_stamp = ora_sysdatetime
      WHERE pv.pv_id = pvid;

      --Now clean the PLANNED_VERSIONS table
      SELECT pkg_id
        INTO pkgid
        FROM PACKAGES
       WHERE pkg_name = pkgname;

      DELETE FROM planned_versions
            WHERE pkg_id = pkgid AND pkg_version = newpkgversion;

      RETURN pvid;
   END;

/*-------------------------------------------------------------------------------------------------------*/
--  import package dependencies (2nd attenpt)
--  Package dependencies are an array of strings. Each string is of the form
--    'PkgName','PkgVersion','PkgType'
--  The use of an array of package dependencies allows packages with very long
--  list of dependencies. More than can be put in to a VARCHAR2
--
   PROCEDURE import_dependencies2 (
      pvid                     IN   NUMBER,
      dependenciesimportlist   IN   relmgr_varchar2_tab_t,
      userid                   IN   NUMBER
   )
   IS

      TYPE tdictionary IS TABLE OF VARCHAR2 (4000) INDEX BY VARCHAR2 (4000);

      seperator         VARCHAR2 (2)           := '||';
      pkgname           VARCHAR2 (4000);
      pkgversion        VARCHAR2 (4000);
      pkgtype           VARCHAR2  (50);
      pkgid             NUMBER;
      vext              VARCHAR2 (4000);
      dpvid             NUMBER;
      cbuildtypes       tdictionary;
      dependencyrow     NUMBER;
      sdependency       VARCHAR2 (4000);
      citemcollection   relmgr_varchar2_tab_t;

      CURSOR curbuildtype
      IS
         SELECT dpv.pkg_id || seperator || dpv.v_ext AS pkgid_ext,
                dep.build_type
           FROM package_dependencies dep, package_versions dpv
          WHERE dep.pv_id = pvid AND dep.dpv_id = dpv.pv_id;

      recbuildtype      curbuildtype%ROWTYPE;
   BEGIN
      -- Get Current Dependencies
      OPEN curbuildtype;

      FETCH curbuildtype
       INTO recbuildtype;

      WHILE curbuildtype%FOUND
      LOOP
         cbuildtypes (recbuildtype.pkgid_ext) := recbuildtype.build_type;
         FETCH curbuildtype INTO recbuildtype;
      END LOOP;

      CLOSE curbuildtype;

      BEGIN
         -- Remove old dependencies
         DELETE FROM package_dependencies dep
               WHERE dep.pv_id = pvid;

         -- Loop through dependencies
         FOR dependencyrow IN 1 .. dependenciesimportlist.COUNT
         LOOP
            -- Extract pkg_name and pkg_version and type(optional)
            sdependency := dependenciesimportlist (dependencyrow);
            sdependency := REPLACE(sdependency, '''');
            sdependency := REPLACE(sdependency, '"');
            -- Remove empty dependency
            IF LENGTH(sdependency) > 0 THEN
              citemcollection := in_list_varchar2 (sdependency, ',');
              IF citemcollection.COUNT  < 2
              THEN
                raise_application_error
                  (-20000,
                      'Dependency ['
                   || sdependency
                   || '] must have at least two ; separated fields!'
                  );
              END IF;
              pkgname := citemcollection(1);
              pkgversion := citemcollection(2);
              IF citemcollection.COUNT >= 3
              THEN
                pkgtype := citemcollection(3);
              ELSE
                pkgtype := NULL;
              END IF;
              -- Dependency must exits to be linked against
              BEGIN
                 SELECT pv.pv_id, pv.pkg_id, pv.v_ext
                   INTO dpvid, pkgid, vext
                   FROM package_versions pv, PACKAGES pkg
                  WHERE pv.pkg_id = pkg.pkg_id
                    AND pkg.pkg_name = pkgname
                    AND pv.pkg_version = pkgversion;
              EXCEPTION
                 WHEN NO_DATA_FOUND
                 THEN
                    raise_application_error
                                    (-20000,
                                        'Dependency ['
                                     || pkgname
                                     || ' '
                                     || pkgversion
                                     || '] does not exist yet and cannot be used!'
                                    );
              END;

              -- Get Build Type (i.e. BuildPackageArchive or LinkPackageArchive)
              IF pkgtype IS NULL
              THEN
                BEGIN
                   pkgtype := cbuildtypes (pkgid || seperator || vext);

                   IF pkgtype IS NULL
                   THEN
                      -- Set build type to LinkPackageArchive by default
                      pkgtype := 'L';
                   END IF;
                EXCEPTION
                   WHEN NO_DATA_FOUND
                   THEN
                      pkgtype := 'L';
                END;
              END IF;

              -- Limit to known types
              IF UPPER(pkgtype) like('B%') THEN
                pkgtype := 'B';
              ELSE
                pkgtype := 'L';
              END IF;  

              -- Insert Dependencies
              update_package_dependency (pvid,
                                         pkgname,
                                         pkgversion,
                                         pkgtype,
                                         userid,
                                         0
                                        );
            END IF;
         END LOOP;
      END;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   FUNCTION return_last_package_version (pkgname IN VARCHAR2, rtagid IN NUMBER)
      RETURN VARCHAR2
   IS
      pkgversion   VARCHAR2 (4000);
   BEGIN
      BEGIN
         SELECT pv.pkg_version
           INTO pkgversion
           FROM PACKAGES pkg, release_content rc, package_versions pv
          WHERE pv.pv_id = rc.pv_id
            AND pkg.pkg_id = pv.pkg_id
            AND pkg.pkg_name = pkgname
            AND rc.rtag_id = rtagid;

         RETURN pkgversion;
      END;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   FUNCTION return_wip (pkgname IN VARCHAR2, rtagid IN NUMBER)
      RETURN VARCHAR2
   IS
      pkgversion   VARCHAR2 (4000);
   BEGIN
      BEGIN
         SELECT pv.pkg_version
           INTO pkgversion
           FROM PACKAGES pkg, work_in_progress wip, package_versions pv
          WHERE pv.pv_id = wip.pv_id
            AND pkg.pkg_id = pv.pkg_id
            AND pkg.pkg_name = pkgname
            AND wip.rtag_id = rtagid;

         IF pkgversion IS NULL
         THEN
            SELECT pv.pkg_version
              INTO pkgversion
              FROM PACKAGES pkg, planned pl, package_versions pv
             WHERE pv.pv_id = pl.pv_id
               AND pkg.pkg_id = pv.pkg_id
               AND pkg.pkg_name = pkgname
               AND pl.rtag_id = rtagid;
         END IF;

         RETURN pkgversion;
      END;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE update_dash_board (rtagid IN NUMBER)
   IS
      projid       NUMBER;
      projiddb     NUMBER;
      total        NUMBER;
      auto_total   NUMBER;
      rtagiddb     NUMBER;
   BEGIN
      SELECT COUNT (*)
        INTO total
        FROM release_content rc, package_versions pv
       WHERE pv.pv_id = rc.pv_id AND rc.rtag_id = rtagid;

      SELECT COUNT (*)
        INTO auto_total
        FROM release_content rc, package_versions pv
       WHERE pv.pv_id = rc.pv_id
         AND pv.is_autobuildable = 'Y'
         AND rc.rtag_id = rtagid;

      BEGIN
         SELECT rtag_id
           INTO rtagiddb
           FROM dash_board
          WHERE rtag_id = rtagid;

         SELECT proj_id
           INTO projiddb
           FROM dash_board
          WHERE rtag_id = rtagid;
      EXCEPTION
         WHEN NO_DATA_FOUND
         THEN
            rtagiddb := '';
      END;

      IF rtagiddb IS NULL
      THEN
         SELECT proj_id
           INTO projid
           FROM release_tags
          WHERE rtag_id = rtagid;

         INSERT INTO dash_board
                     (proj_id, rtag_id, last_build_time, automated_packages,
                      total_packages
                     )
              VALUES (projid, rtagid, ora_sysdatetime, auto_total,
                      total
                     );
      ELSE
         UPDATE dash_board
            SET last_build_time = ora_sysdatetime,
                automated_packages = auto_total,
                total_packages = total
          WHERE proj_id = projiddb AND rtag_id = rtagiddb;
      END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   FUNCTION exclude_from_build (
      pvid          IN   NUMBER,
      spkgversion   IN   VARCHAR2,
      rtagid        IN   NUMBER,
      username      IN   VARCHAR2
   )
      RETURN NUMBER
   IS
      userid              NUMBER;
      outerrcode          NUMBER;
      pkgid               NUMBER;

      CURSOR dnr_duplicate_cur
      IS
         SELECT *
           FROM do_not_ripple
          WHERE pv_id = pvid AND rtag_id = rtagid;

      dnr_duplicate_rec   dnr_duplicate_cur%ROWTYPE;
   BEGIN
      outerrcode := -1;       -- Set default return error code to ERROR state

      /*--------------- Business Rules Here -------------------*/
      IF (rtagid IS NULL)
      THEN
         RETURN outerrcode;
--         raise_application_error (-20000, 'RtagId must be supplied.');
      END IF;

      IF (pvid IS NULL)
      THEN
         RETURN outerrcode;
--         raise_application_error (-20000, 'PvId must be supplied.');
      END IF;

      IF (username IS NULL)
      THEN
         RETURN outerrcode;
--         raise_application_error (-20000, 'UserName must be supplied.');
      END IF;

      -- Get user_id
      BEGIN
         SELECT usr.user_id
           INTO userid
           FROM users usr
          WHERE UPPER (usr.user_name) = UPPER (username)
            AND usr.is_disabled IS NULL;
      EXCEPTION
         WHEN NO_DATA_FOUND
         THEN
            RETURN outerrcode;
--            raise_application_error (-20000,
--                                        'UserName '
--                                     || username
--                                     || ' is not valid or disabled.'
--                                    );
      END;

      OPEN dnr_duplicate_cur;

      FETCH dnr_duplicate_cur
       INTO dnr_duplicate_rec;

      IF dnr_duplicate_cur%FOUND
      THEN
         outerrcode := 0;
      END IF;

      IF dnr_duplicate_cur%NOTFOUND
      THEN
         /* No duplicate recordset */
         unripple_package (pvid, rtagid, userid);
         outerrcode := 0;                            -- Set return to SUCCESS
      END IF;

      CLOSE dnr_duplicate_cur;

      SELECT pkg_id
        INTO pkgid
        FROM package_versions
       WHERE pv_id = pvid;

      DELETE FROM planned_versions
            WHERE pkg_id = pkgid AND pkg_version = spkgversion;

      RETURN outerrcode;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   FUNCTION exclude_indirect_from_build (
      pvid          IN   NUMBER,
      spkgversion   IN   VARCHAR2,
      rtagid        IN   NUMBER,
      username      IN   VARCHAR2,
      rootpvid      IN   NUMBER,
      rootcause     IN   VARCHAR2,
      rootfile      IN   VARCHAR2
   )
      RETURN NUMBER
   IS
      userid              NUMBER;
      outerrcode          NUMBER;
      pkgid               NUMBER;

      CURSOR dnr_duplicate_cur
      IS
         SELECT *
           FROM do_not_ripple
          WHERE pv_id = pvid AND rtag_id = rtagid;

      dnr_duplicate_rec   dnr_duplicate_cur%ROWTYPE;
   BEGIN
      outerrcode := -1;       -- Set default return error code to ERROR state

      /*--------------- Business Rules Here -------------------*/
      IF (rtagid IS NULL)
      THEN
         RETURN outerrcode;
--         raise_application_error (-20000, 'RtagId must be supplied.');
      END IF;

      IF (pvid IS NULL)
      THEN
         RETURN outerrcode;
--         raise_application_error (-20000, 'PvId must be supplied.');
      END IF;

      IF (username IS NULL)
      THEN
         RETURN outerrcode;
--         raise_application_error (-20000, 'UserName must be supplied.');
      END IF;

      -- Get user_id
      BEGIN
         SELECT usr.user_id
           INTO userid
           FROM users usr
          WHERE UPPER (usr.user_name) = UPPER (username)
            AND usr.is_disabled IS NULL;
      EXCEPTION
         WHEN NO_DATA_FOUND
         THEN
            RETURN outerrcode;
--            raise_application_error (-20000,
--                                        'UserName '
--                                     || username
--                                     || ' is not valid or disabled.'
--                                    );
      END;

     /* No duplicate recordset */
     unripple_package_indirect (pvid, rtagid, userid, rootpvid, rootcause, rootfile);
     outerrcode := 0;                            -- Set return to SUCCESS

      SELECT pkg_id
        INTO pkgid
        FROM package_versions
       WHERE pv_id = pvid;

      DELETE FROM planned_versions
            WHERE pkg_id = pkgid AND pkg_version = spkgversion;

      RETURN outerrcode;
   END;
/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE insert_abt_actionlog (rconid IN NUMBER, action IN VARCHAR2)
   IS
   BEGIN
      INSERT INTO abt_action_log
                  (rcon_id, action_datetime, action
                  )
           VALUES (rconid, ora_sysdatetime, action
                  );
   END;

/*-------------------------------------------------------------------------------------------------------*/
   FUNCTION insert_package_metrics (
      rtagid                   IN   NUMBER,
      pkgname                  IN   VARCHAR2,
      vext                     IN   VARCHAR2,
      metricstring             IN   VARCHAR2
   )
      RETURN NUMBER
   IS
      citemcollection          relmgr_varchar2_tab_t  := relmgr_varchar2_tab_t ();
      lv_pvid                  NUMBER                 := 0;
      rownumber                NUMBER;
      rowcontent               VARCHAR2(4000);
      metricname               VARCHAR2(1000);
      metricvalue              VARCHAR2(4000);
      return_insert_error      NUMBER                 := -1;
      return_insert_success    NUMBER                 := 0;

      /* Metrics */
      lv_branches                 NUMBER;
      lv_branchlist               VARCHAR2(4000);
      lv_codefiles                NUMBER;
      lv_ignoredfiles             NUMBER;
      lv_directories              NUMBER;
      lv_directorydepth           NUMBER;
      lv_totalfiles               NUMBER;
      lv_makefiles                NUMBER;
      lv_blanklines               NUMBER;
      lv_codelines                NUMBER;
      lv_commentlines             NUMBER;

   BEGIN
      /*--------------- Business Rules Here -------------------*/
      IF (rtagid IS NULL)
      THEN
         RETURN return_insert_error;
      END IF;

      IF (pkgname IS NULL)
      THEN
         RETURN return_insert_error;
      END IF;

      IF (metricstring IS NULL)
      THEN
         RETURN return_insert_error;
      END IF;

      BEGIN
         SELECT pv.pv_id
           INTO lv_pvid
           FROM package_versions pv, packages pkg, release_content rc
          WHERE pv.pkg_id = pkg.pkg_id
            AND rc.rtag_id = rtagid
            AND pv.pv_id = rc.pv_id
            AND pkg.pkg_name = pkgname
            AND NVL (pv.v_ext, '|LINK_A_NULL|') = NVL (vext, '|LINK_A_NULL|');
      EXCEPTION
           WHEN NO_DATA_FOUND
           THEN
                lv_pvid := 0;
      END;

      citemcollection := in_list_varchar2 (metricstring, ';');

      FOR rownumber IN 1 .. citemcollection.COUNT
      LOOP
         rowcontent := citemcollection(rownumber);
         metricvalue := SUBSTR(rowcontent, (INSTR(rowcontent, '=') + 1));
         metricname := REGEXP_REPLACE(rowcontent, '=.*$', '');

         IF    metricname = 'ccbranch.count' THEN lv_branches := metricvalue;
         ELSIF metricname = 'ccbranch.list' THEN lv_branchlist := metricvalue;
         ELSIF metricname = 'code.files' THEN lv_codefiles := metricvalue;
         ELSIF metricname = 'code.ignored' THEN lv_ignoredfiles := metricvalue;
         ELSIF metricname = 'count.dir' THEN lv_directories := metricvalue;
         ELSIF metricname = 'count.dirdepth' THEN lv_directorydepth := metricvalue;
         ELSIF metricname = 'count.file' THEN lv_totalfiles := metricvalue;
         ELSIF metricname = 'count.makefile' THEN lv_makefiles := metricvalue;
         ELSIF metricname = 'lines.blank' THEN lv_blanklines := metricvalue;
         ELSIF metricname = 'lines.code' THEN lv_codelines := metricvalue;
         ELSIF metricname = 'lines.comment' THEN lv_commentlines := metricvalue;
         END IF;
      END LOOP;

      IF (lv_pvid > 0)
      THEN
         -- Delete any existing entries for this package version to makes sure our data is untainted
         DELETE FROM package_metrics pm
         WHERE pm.pv_id = lv_pvid;

         -- Insert the new data into the metrics table
         INSERT INTO package_metrics
                     (pv_id, branches, branch_list, code_files, ignored_files, directories, directory_depth,
                      total_files, makefiles, blank_lines, code_lines, comment_lines, created_stamp
                     )
              VALUES (lv_pvid, lv_branches, lv_branchlist, lv_codefiles, lv_ignoredfiles, lv_directories, lv_directorydepth,
                      lv_totalfiles, lv_makefiles, lv_blanklines, lv_codelines, lv_commentlines, ora_sysdatetime
                     );

         -- Now update the Release_Metrics Table
         update_release_metrics(rtagid);

         RETURN return_insert_success;
      ELSE
         RETURN return_insert_error;
      END IF;
   END;

/*-------------------------------------------------------------------------------------------------------*/
   PROCEDURE update_release_metrics (rtagid IN NUMBER)
   IS
      lv_totalpackages       NUMBER;
      lv_autobuilt           NUMBER;
      lv_linesofcode         NUMBER;
      lv_unittested          NUMBER;
      lv_autotested          NUMBER;
      lv_numOfbranches       NUMBER;
      lv_lastbuildtime       DATE;
   BEGIN
      IF (rtagid > 0)
      THEN
         -- Get the total number of packages in this release and the number of
         -- those that are autobuilt
         SELECT COUNT (DISTINCT rc.pv_id),
                COUNT (DISTINCT autobuilt_qry.pv_id)
           INTO lv_totalpackages, lv_autobuilt
           FROM release_content rc,
                package_versions pv,
                (
                 SELECT rc.pv_id
                   FROM release_content rc,
                        package_versions pv
                  WHERE pv.is_autobuildable = 'Y'
                    AND pv.pv_id = rc.pv_id
                    AND rc.rtag_id = rtagid
                ) autobuilt_qry
          WHERE pv.pv_id = rc.pv_id
            AND rc.rtag_id = rtagid
            AND autobuilt_qry.pv_id (+) = rc.pv_id;

         -- Get the build time of the last package built in this release and the
         -- total number of lines of code
         SELECT MAX(pm.created_stamp),
                SUM(pm.code_lines)
           INTO lv_lastbuildtime, lv_linesofcode
           FROM package_metrics pm, release_content rc
          WHERE pm.pv_id = rc.pv_id
            AND rc.rtag_id = rtagid;

         -- Get the number of packages with unit tests in this release and the
         -- number of those that are autotested
         SELECT COUNT(DISTINCT ut.pv_id) INTO lv_unittested
           FROM unit_tests ut,
                release_content rc
          WHERE ut.pv_id = rc.pv_id
            AND rc.rtag_id = rtagid
        AND ut.test_types_fk != 1;

        SELECT COUNT(DISTINCT ut.pv_id) INTO lv_autotested
          FROM unit_tests ut,
               release_content rc
         WHERE ut.pv_id = rc.pv_id
           AND rc.rtag_id = rtagid
           AND ut.test_types_fk = 7;


         -- Count the number of unique branches in the packages in this release.
--         SELECT COUNT(DISTINCT branch) INTO lv_numOfbranches
--           FROM (
--                SELECT pv_id,
--                       regexp_substr(str, '[^,]+', 1, level) branch,
--                       level lv,
--                       lag(level, 1, 0) over (partition by pv_id order by level) lg
--                  FROM (
--                       SELECT pm.pv_id,
--                              ','||pm.branch_list str
--                         FROM package_metrics pm,
--                              release_content rc
--                        WHERE pm.pv_id = rc.pv_id
--                          AND rc.rtag_id = rtagid
--                       )
--                CONNECT BY regexp_substr(str, '[^,]+', 1, LEVEL) IS NOT NULL
--                )
--          WHERE lv != lg;

         UPDATE release_metrics rm
            SET rm.total_packages = lv_totalpackages,
                rm.autobuilt = lv_autobuilt,
                rm.lines_of_code = lv_linesofcode,
                rm.unit_tested = lv_unittested,
                rm.autotested = lv_autotested,
--                rm.branches = lv_numOfbranches,
                rm.last_build_time = lv_lastbuildtime
          WHERE rtag_id = rtagid;

         IF (SQL%ROWCOUNT = 0)
         THEN
            INSERT INTO release_metrics
                        (rtag_id, total_packages, autobuilt, lines_of_code, unit_tested,
                         autotested, last_build_time
                        )
                 VALUES (rtagid, lv_totalpackages, lv_autobuilt, lv_linesofcode, lv_unittested,
                         lv_autotested, lv_lastbuildtime
                        );
         END IF;
--         IF (SQL%ROWCOUNT = 0)
--         THEN
--            INSERT INTO release_metrics
--                        (rtag_id, total_packages, autobuilt, lines_of_code, unit_tested,
--                         autotested, branches, last_build_time
--                        )
--                 VALUES (rtagid, lv_totalpackages, lv_autobuilt, lv_linesofcode, lv_unittested,
--                         lv_autotested, lv_numOfbranches, lv_lastbuildtime
--                        );
--         END IF;
--      ELSE
--         raise_application_error (-20000, 'RtagId must be supplied.');
      END IF;
   END;
/*-------------------------------------------------------------------------------------------------------*/
   FUNCTION return_vcs_tag(pvid IN NUMBER) RETURN VARCHAR2
   IS
      vcstypeid    NUMBER;
      vcstag       VARCHAR2(32);
      label        VARCHAR2(60);
      srcpath      VARCHAR2(2000);
      vcstypeid_cc NUMBER;
      vcstypeid_uc NUMBER;
   BEGIN
      -- Get the VCS_TYPE_ID for the ClearCase version control system. We do this so that we make no assumptions about
      -- what the primary key value is for the ClearCase VCS entry.
      BEGIN
         SELECT vt.vcs_type_id
         INTO vcstypeid_cc
         FROM VCS_TYPE vt
         WHERE vt.tag = 'CC';
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               raise_application_error (-20000, 'Database is missing compulsory CC version control system tag!');
      END;

      -- Get the VCS_TYPE_ID for the Uncontrolled version control system. We do this so that we make no assumptions about
      -- what the primary key value is for the Uncontrolled VCS entry.
      BEGIN
         SELECT vt.vcs_type_id
         INTO vcstypeid_uc
         FROM VCS_TYPE vt
         WHERE vt.tag = 'UC';
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               raise_application_error (-20000, 'Database is missing compulsory UC version control system tag!');
      END;

      -- Get the PKG_LABEL, SRC_PATH, VCS_TYPE_ID for the package version
      -- As additional VCS types are introduced, we may have to extend what this SELECT statement returns
      BEGIN
         SELECT pv.pkg_label, pv.src_path,
           (CASE WHEN pv.pkg_label = 'N/A' AND pv.vcs_type_id IS NULL THEN vcstypeid_uc
                 WHEN pv.vcs_type_id IS NULL THEN vcstypeid_cc
                 ELSE pv.vcs_type_id END) AS vcs_type_id
         INTO label, srcpath, vcstypeid
         FROM PACKAGE_VERSIONS pv
         WHERE pv.pv_id = pvid;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               raise_application_error (-20000, 'Package Version Not Found!');
      END;

      -- Get the VCS TAG for the VCS_TYPE_ID.
      BEGIN
         SELECT vt.tag
         INTO vcstag
         FROM VCS_TYPE vt
         WHERE vt.vcs_type_id = vcstypeid;
         EXCEPTION
            WHEN NO_DATA_FOUND THEN
               raise_application_error (-20000, 'Could not get VCS Tag for the package version!');
      END;

      -- Return value depending upon which VCS Tag is being used.
      -- As additional VCS types are introduced, we have to add additional WHEN clauses
      CASE vcstag
         WHEN 'CC' THEN
            RETURN vcstag || '::' || srcpath || '::' || label;
         WHEN 'SVN' THEN
            RETURN vcstag || '::' || srcpath || '::' || label;
         ELSE
            RETURN vcstag || '::';
      END CASE;

   END;
/*-------------------------------------------------------------------------------------------------------*/

/*-------------------------------------------------------------------------------------------------------
Name:        update_vcs_details
Description: Updates the Version Control System (vcs) details specified in the vcstag
             parameter for the specified package version.
             The specified package vcstag is parsed and split into 3 fields:
                vcs type, src path, label
             These fields are then stored for the specified pv_id in the package_versions, table.
             An action is recorded in the action log and provides information for tracking and
             for restoring the previous vcs settings if a recovery is required.
Paramters:
             ipv_id:     Package version identifier
             vcstag:     Full version control tag.
                         Examples:
                             "SVN::AUPERASVN01/DPG_SWBase/tools/trunk::daf_tools_25.1.7027.cr@1234"
                            "CC::/DPG_SWBase/tools::daf_tools_25.1.7016.cr"
             user_id:    Identifier of the user that is performing this function.
*/
PROCEDURE update_vcs_details(ipv_id IN NUMBER, vcstag IN VARCHAR2, user_id IN NUMBER)
   IS
      ivcs_type_id   NUMBER;
      svcs_type      VARCHAR2(128);
      ssrc_path      VARCHAR2(512);
      spkg_label     VARCHAR2(512);
      spattern       VARCHAR2(64);
      saction_desc   VARCHAR2(2048);
      old_vcs_type   VARCHAR2(128);
      old_src_path   VARCHAR2(512);
      old_pkg_label  VARCHAR2(512);
      old_pkg_vcstag VARCHAR2(1024);
      i              NUMBER;
      vcount         NUMBER;
   BEGIN
     -- Split vcs tag into fields: vcs type, src path, label
     -- Fields are separated by '::'
     -- e.g "CC::/DPG_SWBase/tools::daf_tools_25.1.7016.cr"
     -- The below regular expression pattern has groups to achieve this.

     spattern:= '^([^:]*)::([^:]*)(::(.*))?$';

     --As Oracle 10g does not allow REGEXP_SUBSTR to return a group,
     --REGEXP_REPLACE is used instead (Note: Oracle 11g has this enhancement).
     SELECT REGEXP_REPLACE(vcstag,spattern, '\1') INTO svcs_type  FROM DUAL;
     SELECT REGEXP_REPLACE(vcstag,spattern, '\2') INTO ssrc_path  FROM DUAL;
     SELECT REGEXP_REPLACE(vcstag,spattern, '\4') INTO spkg_label FROM DUAL;

     -- Validate vcs type
     BEGIN
       SELECT vc.vcs_type_id INTO ivcs_type_id FROM vcs_type vc WHERE UPPER(svcs_type) = UPPER(vc.tag);
     EXCEPTION
       WHEN NO_DATA_FOUND THEN
         raise_application_error (-20000, 'Invalid vcs type: ' || '"' || svcs_type || '"' || ' for package version: ' || ipv_id || ', vcstag: ' || '"' || vcstag || '"');
       --RAISE;
     END;

     -- If Clearcase
     IF (ivcs_type_id = 2) THEN
       -- Validate source path
       IF NOT REGEXP_LIKE(ssrc_path,'^(\\|\/)[a-z]+[0-9a-z_\.\-\\\/ -]*$','i') THEN
         raise_application_error (-20000, 'Invalid CC src path: ' || '"' || ssrc_path || '"' || ' for package version: ' || ipv_id || ', vcstag: ' || '"' || vcstag || '"');
       END IF;

       -- Validate label
       -- For clearcase the label must be specified. For subversion it is not required.
       IF NOT REGEXP_LIKE(spkg_label,'^[0-9a-z_\.\-]+$','i') THEN
         raise_application_error (-20000, 'Invalid CC label:' || '"' || spkg_label || '"' || ' for package version:' || ipv_id || ', vcstag:' || '"' || vcstag || '"');
       END IF;

     -- if Subversion
     ELSIF (ivcs_type_id = 23) THEN
       -- general validity
       -- Not as picky as the RM Data entry
       IF NOT REGEXP_LIKE(ssrc_path,'^([0-9a-z_\.\-]+)(\/([0-9a-z_\.\-]+))+$','i') THEN
         raise_application_error (-20000, 'Invalid SVN src path: ' || '"' || ssrc_path || '"' || ' for package version: ' || ipv_id || ', vcstag: ' || '"' || vcstag || '"');
       END IF;

       -- Validate Tag
       -- May be a Peg or a Label
       IF NOT REGEXP_LIKE(spkg_label,'^@?[0-9]+$','i') THEN
           IF NOT REGEXP_LIKE(spkg_label,'^[0-9a-z_\.\-]+($|@[0-9]+)','i') THEN
             raise_application_error (-20000, 'Invalid SVN tag:' || '"' || spkg_label || '"' || ' for package version:' || ipv_id || ', vcstag:' || '"' || vcstag || '"');
           END IF;
       END IF;

        -- Check for suitable ending
        IF NOT REGEXP_LIKE(ssrc_path,'(\/tags$)|(\/branches\/)|(\/trunk$)','i') THEN
            raise_application_error (-20000, 'Must end in /trunk or /tags/ or /branches/.... Invalid SVN src path: ' || '"' || ssrc_path || '"' || ' for package version: ' || ipv_id || ', vcstag: ' || '"' || vcstag || '"');
        END IF;

       -- Check for combined use of tags, branches, trunk or repeats of each
       -- Count occurrences of /tags or /branches/ or /trunk
       vcount:=0;
       i:=1;
       WHILE i > 0 LOOP
         i:=REGEXP_INSTR(ssrc_path,'(\/tags(\/|$))|(\/branches(\/|$))|(\/trunk(\/|$))',i,1,1,'i');
         IF i > 0 THEN
           -- if found then increment count
           vcount:=vcount+1;
           i:=i-1;  -- move index back to "/"
         END IF;
       END LOOP;

       IF vcount = 0  THEN
         raise_application_error (-20000, 'Must contain exactly one of the keywords /trunk, /tags, /branches/. Invalid SVN src path: ' || '"' || ssrc_path || '"' || ' for package version: ' || ipv_id || ', vcstag: ' || '"' || vcstag || '"');
       END IF;

       IF vcount > 1  THEN
         raise_application_error (-20000, 'Combined use of /trunk, /tags, or /branches/. Invalid SVN src path: ' || '"' || ssrc_path || '"' || ' for package version: ' || ipv_id || ', vcstag: ' || '"' || vcstag || '"');
       END IF;


     END IF;

     BEGIN
       -- Get current vcs tag for specified package version
       SELECT pv.src_path, pv.pkg_label, vc.tag as vcs_type
       INTO old_src_path, old_pkg_label, old_vcs_type
       FROM package_versions pv, vcs_type vc
       WHERE pv.pv_id = ipv_id
       AND pv.vcs_type_id = vc.vcs_type_id (+);

     EXCEPTION
       WHEN NO_DATA_FOUND THEN
         raise_application_error (-20000, 'Package version not found: ' || ipv_id);
     END;

     old_pkg_vcstag:= old_vcs_type || '::' || old_src_path;
     IF (old_pkg_label IS NOT NULL) THEN
       old_pkg_vcstag:=old_pkg_vcstag || '::' || old_pkg_label;
     END IF;

     -- Create action description
     -- This description will contain the old and new tags.
     -- Its purpose is to provide information for tracking and for restoring previous vcs settings if a recovery is required.
     -- An example of the action description is below:
     --   OldTag:CC::/DPG_SWBase/tools::daf_tools_25.1.7016.cr NewTag:SVN::DPG_SWBase/tools/tags/daf_tools_25.1.7027.cr
     saction_desc:='OldTag:' || old_pkg_vcstag || ' ' || 'NewTag:' || vcstag;

     -- Store new vcs details
     UPDATE package_versions SET
       src_path = ssrc_path,
       pkg_label = spkg_label,
       vcs_type_id = ivcs_type_id
     WHERE
       pv_id = ipv_id;

     -- Store action in action log so that we can back track and also restore vcs settings if required.
     log_action (ipv_id,'VcsConversion',user_id,saction_desc);

   END update_vcs_details;

/*-------------------------------------------------------------------------------------------------------
Name:        isSVN
Description: Determine if any of the packages versions are controlled under SVN
			 Intended to be used to prevent users from releasing a package
			 that has been migrated to SVN

Paramters:	pkgid:     Package ID

Returns:	Number of versions under SVN version control
*/

FUNCTION isSVN( pkgid IN NUMBER )
    RETURN NUMBER
    IS
    svncount   NUMBER  := 0;
   BEGIN
        SELECT COUNT(*) INTO svncount FROM PACKAGE_VERSIONS pv WHERE pv.PKG_ID = pkgid AND pv.VCS_TYPE_ID = 23;
        RETURN (svncount);
   END;

/*-------------------------------------------------------------------------------------------------------
Name:        isSVNbyName
Description: Determine if any of the packages versions are controlled under SVN
			 Intended to be used to prevent users from releasing a package
			 that has been migrated to SVN

Paramters:	pkgname:	Package Name

Returns:	Number of versions under SVN version control
*/

FUNCTION isSVNbyName( pkgname IN VARCHAR2 )
    RETURN NUMBER
IS
   svncount   NUMBER  := 0;
   BEGIN
        SELECT COUNT(*) INTO svncount FROM PACKAGE_VERSIONS pv, PACKAGES pkg WHERE pkg.pkg_name = pkgname AND pv.PKG_ID = pkg.pkg_id AND pv.VCS_TYPE_ID = 23;
        RETURN (svncount);
   END;
/*-------------------------------------------------------------------------------------------------------
Name:        new_build_instance
Description: Create a new entry in the BUILD_INSTANCE table
             The BUILD_ID will be allocated.
             The timestamp will be created

Paramters:	rtag_id:	Release ID - must exist
            pv_id:    Package ID - must exist
            reason:   Reason code for the build
            buildRef: Identify build logs

Returns:	BUILD_ID for the new entry
          Returns -1 on error, PV_ID or RTAG_ID do not exist
*/
FUNCTION new_build_instance( rtag_id IN NUMBER, pv_id IN NUMBER , reason IN CHAR, buildRef IN VARCHAR2)
  RETURN NUMBER
  IS
    build_id NUMBER := 0;
  BEGIN
    INSERT into BUILD_INSTANCES (RTAG_ID, PV_ID, REASON, BUILD_REF)
    values( rtag_id, pv_id, reason, buildRef)
    returning BUILD_ID into build_id;
    return build_id;
  EXCEPTION
    WHEN OTHERS THEN
      return -1;
  END;

/*-------------------------------------------------------------------------------------------------------
Name: update_build_instance
Description: Update fields in an existing build instance
Returns: -1 on error
*/
FUNCTION update_build_instance(
    nbuild_id IN NUMBER,
    npv_id    IN NUMBER DEFAULT NULL,
    nstate    IN CHAR DEFAULT NULL )
  RETURN NUMBER
IS
BEGIN
  IF ( npv_id IS NOT NULL AND npv_id > 0 ) THEN
    UPDATE BUILD_INSTANCES SET PV_ID = npv_id WHERE BUILD_ID = nbuild_id;
    IF SQL%NOTFOUND THEN
      RETURN -2;
    END IF;
  END IF;

  IF ( nstate        IS NOT NULL ) THEN
    IF (LENGTH(nstate) = 1 ) THEN
      UPDATE BUILD_INSTANCES SET STATE = nstate WHERE BUILD_ID = nbuild_id;
        IF SQL%NOTFOUND THEN
          RETURN -3;
        END IF;
    ELSE
      RETURN -4;
    END IF;
  END IF;

  RETURN 1;
  EXCEPTION
    WHEN OTHERS THEN
      RETURN -1;
  END;

/*-------------------------------------------------------------------------------------------------------
Name: update_build_instance
Description: Update fields in an existing build instance
Returns: -1 on error
*/
FUNCTION update_build_ref( nrtag_id IN NUMBER, buildRef IN VARCHAR2, buildRefNew IN VARCHAR2 ) RETURN NUMBER
IS
BEGIN
  IF ( nrtag_id IS NOT NULL AND nrtag_id > 0 ) THEN
    UPDATE BUILD_INSTANCES SET BUILD_REF = buildRefNew WHERE nrtag_id = RTAG_ID AND UPPER(BUILD_REF) = UPPER(buildRef);
    IF SQL%NOTFOUND THEN
      RETURN -2;
    END IF;
  END IF;

  RETURN 1;
  EXCEPTION
    WHEN OTHERS THEN
      RETURN -1;
  END;

/*-------------------------------------------------------------------------------------------------------
Name:        insert_test_run
Description: Insert data into the test_run table


Paramters:	See below

Returns:	1 on success
          Returns -1 on error
*/
  FUNCTION insert_test_run(
      build_id  IN NUMBER,
      name      IN VARCHAR2,
      outcome   IN VARCHAR2,
      platform  IN VARCHAR2,
      stype     IN VARCHAR2,
      duration  IN NUMBER default null,
      message   IN CLOB default null
      ) return NUMBER
IS
  sName VARCHAR2(1000) := name;
  sNameLen NUMBER;

BEGIN
  sNameLen := LENGTH(sName);
  IF sNameLen >= 199 Then
    sName := '...' || SUBSTR(sName, sNameLen - 196);
  END IF;

  INSERT into TEST_RUN
    (BUILD_ID, TEST_NAME, TEST_OUTCOME, TIME_TAKEN,FAIL_MESSAGE,PLATFORM, TYPE)
    VALUES(build_id,sName,outcome, duration, message, platform, stype);
    return 1;
  EXCEPTION
    WHEN OTHERS THEN
      return -1;

END;

   END;

/

  GRANT EXECUTE ON "RELEASE_MANAGER"."PK_RMAPI" TO "RM_READONLY";
  GRANT EXECUTE ON "RELEASE_MANAGER"."PK_RMAPI" TO "MS_READONLY";
  GRANT EXECUTE ON "RELEASE_MANAGER"."PK_RMAPI" TO "DM_READONLY";
--------------------------------------------------------
--  DDL for Package Body PK_WORK_IN_PROGRESS
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE BODY "RELEASE_MANAGER"."PK_WORK_IN_PROGRESS" IS

/*
------------------------------
||  Last Modified:  S.Vukovic
||  Modified Date:  2/May/2005
||  Body Version:   1.0
------------------------------
*/


/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE ADD_PACKAGE ( newPvId IN NUMBER, ViewId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER ) IS

	oldPvId NUMBER;
	ReleaseLocation VARCHAR2(4000);
	sLocation VARCHAR2(4000) := NULL;


BEGIN
	/*--------------- Business Rules Here -------------------*/
	/*-------------------------------------------------------*/

	BEGIN
		-- Check if Exists in "Work in progress" anywhere in the world in a non-closed Release
		SELECT proj.PROJ_NAME ||' > '|| rt.RTAG_NAME  INTO sLocation
		  FROM WORK_IN_PROGRESS wip,
		  	   RELEASE_TAGS rt,
			   PROJECTS proj
		 WHERE wip.PV_ID = newPvId
		   AND wip.RTAG_ID = rt.RTAG_ID
		   AND rt.OFFICIAL in ('N','R','C')
		   AND rt.PROJ_ID = proj.PROJ_ID;

		EXCEPTION
	    	WHEN NO_DATA_FOUND THEN
	       		sLocation := NULL;

	END;



	IF (sLocation IS NULL)  THEN

		-- Add to "Work in progress"
		INSERT INTO WORK_IN_PROGRESS ( RTAG_ID, PV_ID, VIEW_ID )
		VALUES( RtagId, newPvId, ViewId );


	    /* LOG ACTION */
		SELECT proj.PROJ_NAME ||' / '|| rt.RTAG_NAME INTO ReleaseLocation
		  FROM PROJECTS proj,
		  	   RELEASE_TAGS rt
		 WHERE rt.PROJ_ID = proj.PROJ_ID
		   AND rt.RTAG_ID = RtagId;

		Log_Action ( newPvId, 'work_in_progress', UserId, 'Location: '|| ReleaseLocation );

	ELSE

		RAISE_APPLICATION_ERROR (-20000, 'This version is already in Work-In-Progress Area at '|| sLocation ||'.' );

	END IF;

END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE REMOVE_PACKAGE ( PvId IN NUMBER, RtagId IN NUMBER, UserId IN NUMBER ) IS

	ReleaseLocation VARCHAR2(4000);

BEGIN

	/*--------------- Business Rules Here -------------------*/
	/*-------------------------------------------------------*/


	-- Get release location for logging pusposes
	SELECT proj.PROJ_NAME ||' / '|| rt.RTAG_NAME INTO ReleaseLocation
	  FROM PROJECTS proj,
	  	   RELEASE_TAGS rt
	 WHERE rt.PROJ_ID = proj.PROJ_ID
	   AND rt.RTAG_ID = RtagId;

    -- Ensure that package is not marked as Pending/Rejected any more
    UPDATE package_versions
       SET DLOCKED  = 'N'
     WHERE PV_ID  = PvId
       AND DLOCKED != 'Y';

	-- Delete from Work In Progress
	DELETE
	  FROM WORK_IN_PROGRESS wip
	 WHERE wip.RTAG_ID = RtagId
	   AND wip.PV_ID = PvId;

	Log_Action ( PvId, 'delete_from_wip', UserId, 'Location: '|| ReleaseLocation );




END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE REMOVE_PACKAGE_BULK ( PvIdList IN VARCHAR2, RtagId IN NUMBER, UserId IN NUMBER ) IS

	nIdCollector RELMGR_NUMBER_TAB_t := RELMGR_NUMBER_TAB_t();
	ReleaseLocation VARCHAR2(4000);
	PvId NUMBER;

BEGIN

	/*--------------- Business Rules Here -------------------*/
	IF (PvIdList IS NULL)
	THEN
		RAISE_APPLICATION_ERROR (-20000, 'Please select at least one package.' );
	END IF;
	/*-------------------------------------------------------*/


	nIdCollector := IN_LIST_NUMBER ( PvIdList );


	-- Get release location for logging pusposes
	SELECT proj.PROJ_NAME  ||' / '|| rt.RTAG_NAME INTO ReleaseLocation
	  FROM PROJECTS proj,
	  	   RELEASE_TAGS rt
	 WHERE rt.PROJ_ID = proj.PROJ_ID
	   AND rt.RTAG_ID = RtagId;


	FOR i IN 1..nIdCollector.COUNT
	LOOP
		PvId := nIdCollector(i);

		-- Delete from Work In Progress
		DELETE
		  FROM WORK_IN_PROGRESS wip
		 WHERE wip.RTAG_ID = RtagId
		   AND wip.PV_ID = PvId;

		Log_Action ( PvId, 'remove_from_work_in_progress', UserId, 'Location: '|| ReleaseLocation );

	END LOOP;


END;
/*-------------------------------------------------------------------------------------------------------*/
FUNCTION GET_PACKAGE_VIEW ( PvId IN NUMBER, RtagId IN NUMBER ) RETURN NUMBER IS

	ReturnValue NUMBER;

BEGIN
	SELECT wip.VIEW_ID INTO ReturnValue
	  FROM WORK_IN_PROGRESS wip
	 WHERE wip.RTAG_ID = RtagId
	   AND wip.PV_ID = PvId;

	RETURN ReturnValue;
END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE GET_VIEW_CONTENT ( RtagId IN NUMBER, ViewId IN NUMBER, RecordSet OUT typeCur ) IS

	IsBaseView CHAR(1);

BEGIN

	-- Check if the view is BASE VIEW
	SELECT vi.BASE_VIEW INTO IsBaseView
	  FROM VIEWS vi
	 WHERE vi.VIEW_ID = ViewId;

	IF (IsBaseView IN ('Y', 'S')) THEN
		-- Get Base view content
		OPEN RecordSet FOR
		SELECT 0 AS PKG_STATE,
			   NULL AS DEPRECATED_STATE,
			   pv.pv_id,
			   pkg.pkg_name,
			   pv.pkg_version,
			   pv.dlocked,
			   pv.pv_description,
			   pv.BUILD_TYPE
		  FROM WORK_IN_PROGRESS rel,
		       packages pkg,
		       package_versions pv
		 WHERE pv.pkg_id = pkg.pkg_id
		   AND rel.pv_id = pv.pv_id
		   AND rel.VIEW_ID = ViewId
		   AND rel.RTAG_ID = RtagId
		 ORDER BY UPPER(pkg.PKG_NAME);


	ELSE

	 	-- Get non base view content
		OPEN RecordSet FOR
		SELECT 0 AS PKG_STATE,
			   NULL AS DEPRECATED_STATE,
			   pv.pv_id,
			   pkg.pkg_name,
			   pv.pkg_version,
			   pv.dlocked,
			   pv.pv_description,
			   pv.BUILD_TYPE
		  FROM WORK_IN_PROGRESS rel,
		       packages pkg,
		       package_versions pv,
			   VIEW_DEF vd
		 WHERE pv.pkg_id = pkg.pkg_id
		   AND rel.pv_id = pv.pv_id
		   AND vd.VIEW_ID = ViewId
		   AND vd.PKG_ID = pv.PKG_ID
		   AND rel.RTAG_ID = RtagId
		 ORDER BY UPPER(pkg.PKG_NAME);


	END IF;


END;
/*-------------------------------------------------------------------------------------------------------*/
PROCEDURE CHANGE_PACKAGE_VIEW ( PvId IN NUMBER, RtagId IN NUMBER, NewViewId IN NUMBER ) IS

BEGIN

	UPDATE WORK_IN_PROGRESS wip SET
	wip.VIEW_ID = NewViewId
	WHERE wip.PV_ID = PvId
	  AND wip.RTAG_ID = RtagId;

END;
/*-------------------------------------------------------------------------------------------------------*/
END PK_WORK_IN_PROGRESS;

/
--------------------------------------------------------
--  DDL for Package Body RM_ISSUES
--------------------------------------------------------

  CREATE OR REPLACE PACKAGE BODY "RELEASE_MANAGER"."RM_ISSUES" AS

-- Private Implementation -----------------------------------------------------


	FUNCTION VerIsGrtrThanOrEqlToStart( XXstart IN NUMBER, XX IN NUMBER, YYstart IN NUMBER, YY IN NUMBER, ZZstart IN NUMBER, ZZ IN NUMBER ) RETURN NUMBER
	AS

	BEGIN
		-- start boundary case
		IF ( XXstart < XX ) THEN
			RETURN 1;

		ELSIF ( XXstart = XX ) THEN

			-- need to consider YY
			IF ( YYstart < YY ) THEN
				RETURN 1;

			ELSIF ( YYstart = YY ) THEN

					-- need to consider ZZ
					IF ( ZZstart <= ZZ ) THEN
						RETURN 1;

					ELSE
						RETURN 0;
					END IF;

			ELSE
				RETURN 0;
			END IF;
		ELSE
			RETURN 0;
		END IF;
	EXCEPTION
		WHEN OTHERS THEN
			RETURN -1;
	END;


	FUNCTION VerIsLessThanOrEqlToEnd( XXend IN NUMBER, XX IN NUMBER, YYend IN NUMBER, YY IN NUMBER, ZZend IN NUMBER, ZZ IN NUMBER ) RETURN NUMBER
	AS

	BEGIN
		-- end boundary case
		IF ( XX < XXend ) THEN
			RETURN 1;

		ELSIF ( XX = XXend ) THEN

			-- need to consider YY
			IF ( YY < YYend ) THEN
				RETURN 1;

			ELSIF ( YY = YYend ) THEN

					-- need to consider ZZ
					IF ( ZZ <= ZZend ) THEN
						RETURN 1;

					ELSE
						RETURN 0;
					END IF;
			ELSE

				RETURN 0;
			END IF;
		ELSE
			RETURN 0;
		END IF;
	EXCEPTION
		WHEN OTHERS THEN
			RETURN -1;
	END;

	/*
	-	version format:		XX.YY.ZZ.abc
	*/
	FUNCTION VersionIsBetween( version IN VARCHAR2, version_start IN VARCHAR2, version_end IN VARCHAR ) RETURN NUMBER
	AS
		XXstart		NUMBER	:=	0;
		XXend		NUMBER	:=	0;
		XX			NUMBER	:=	0;
		YYstart		NUMBER	:=	0;
		YYend		NUMBER	:=	0;
		YY			NUMBER	:=	0;
		ZZstart		NUMBER	:=	0;
		ZZend		NUMBER	:=	0;
		ZZ			NUMBER	:=	0;
		first_dot	NUMBER	:=	0;
		second_dot	NUMBER	:=	0;
		third_dot	NUMBER	:=	0;

		ProjExtstart	VARCHAR2(10);
		ProjExtend		VARCHAR2(10);
		ProjExt			VARCHAR2(10);

	BEGIN
		-- strip the version number
		first_dot :=  INSTR(version_start, '.', 1, 1);
		second_dot :=  INSTR(version_start, '.', 1, 2);
		third_dot :=  INSTR(version_start, '.', 1, 3);

		XXstart := TO_NUMBER( SUBSTR( version_start, 1, first_dot - 1 ) );
		YYstart := TO_NUMBER( SUBSTR( version_start, first_dot + 1, second_dot - ( first_dot + 1 ) ) );
		ZZstart := TO_NUMBER( SUBSTR( version_start, second_dot + 1, third_dot - ( second_dot + 1 ) ) );
		ProjExtstart := SUBSTR( version_start, third_dot + 1, LENGTH(version_start) - third_dot );

		first_dot :=  INSTR(version_end, '.', 1, 1);
		second_dot :=  INSTR(version_end, '.', 1, 2);
		third_dot :=  INSTR(version_end, '.', 1, 3);

		XXend := TO_NUMBER( SUBSTR( version_end, 1, first_dot - 1 ) );
		YYend := TO_NUMBER( SUBSTR( version_end, first_dot + 1, second_dot - ( first_dot + 1 ) ) );
		ZZend := TO_NUMBER( SUBSTR( version_end, second_dot + 1, third_dot - ( second_dot + 1 ) ) );
		ProjExtend := SUBSTR( version_end, third_dot + 1, LENGTH(version_end) - third_dot );

		first_dot :=  INSTR(version, '.', 1, 1);
		second_dot :=  INSTR(version, '.', 1, 2);
		third_dot :=  INSTR(version, '.', 1, 3);

		XX := TO_NUMBER( SUBSTR( version, 1, first_dot - 1 ) );
		YY := TO_NUMBER( SUBSTR( version, first_dot + 1, second_dot - ( first_dot + 1 ) ) );
		ZZ := TO_NUMBER( SUBSTR( version, second_dot + 1, third_dot - ( second_dot + 1 ) ) );
		ProjExt := SUBSTR( version, third_dot + 1, LENGTH(version) - third_dot );

		-- only include versions if all project extensions are the same
		IF ( ProjExtstart = ProjExt AND ProjExt = ProjExtend ) THEN

			IF ( VerIsGrtrThanOrEqlToStart( XXstart, XX, YYstart, YY, ZZstart, ZZ ) = 1 AND VerIsLessThanOrEqlToEnd( XXend, XX, YYend, YY, ZZend, ZZ ) = 1 ) THEN
				RETURN 1;
			ELSE
				RETURN 0;
			END IF;
		ELSE
			RETURN 0;
		END IF;

	EXCEPTION
		WHEN OTHERS THEN
			RETURN -1;
	END;

	FUNCTION GetPkgId( pkgName IN VARCHAR2 ) RETURN NUMBER
	AS
	    pkg_id NUMBER;
	BEGIN
		SELECT
			p.PKG_ID
		INTO
			pkg_id
		FROM
			PACKAGES p
		WHERE
			p.PKG_NAME = pkgName;

		RETURN pkg_id;
	EXCEPTION
	    WHEN OTHERS THEN
			dbms_output.put_line('GetPkgId exception: ' || SQLERRM );
			RETURN -1;
	END;


-- Public Implementation ------------------------------------------------------

	/*
	-- Proc: AllIssues - Gets all issues for a package from dependent packages one level deep
	--
	-- INPUT PARAMETERS:
	--
	--		pkg_name  	-  	The name of the top level package to get issues for
	--		version_start	-	The start version for the comparison
	--		version_end	-	The end version for the comparison
	*/
	PROCEDURE AllIssues( vCursor OUT T_Cur, pkg_name IN VARCHAR2, version_start IN VARCHAR2, version_end IN VARCHAR2 )
	AS
		pkgId	NUMBER;
	BEGIN
		-- get pkg_id of the input package:
		pkgId := GetPkgId( pkg_name );

		OPEN vCursor FOR
		SELECT
			  pv.PKG_ID,
			  pv.PKG_VERSION,
			  pv.PV_ID,
			  i_pkg.ISS_ID,
			  ( SELECT pkg_name FROM PACKAGES WHERE pkg_id = pd.DPKG_ID ) AS DPV_NAME,
			  pd.DPKG_ID,
			  ( SELECT pkg_version FROM PACKAGE_VERSIONS WHERE pv_id = pd.DPV_ID ) AS DPV_VER,
			  pd.DPV_ID,
			  i_dpkg.ISS_ID AS ISSUE_ID
		FROM
			 PACKAGE_VERSIONS pv
							  LEFT OUTER JOIN CQ_ISSUES i_pkg ON pv.PV_ID = i_pkg.PV_ID
							  LEFT OUTER JOIN PACKAGE_DEPENDENCIES pd ON pv.PV_ID = pd.PV_ID
							  LEFT OUTER JOIN CQ_ISSUES i_dpkg ON pd.DPV_ID = i_dpkg.PV_ID
		WHERE
   			 pv.PKG_ID = pkgId
		AND
			VersionIsBetween( pv.PKG_VERSION, version_start, version_end ) = 1
		AND
			 ( i_dpkg.ISS_ID IS NOT NULL OR i_pkg.ISS_ID IS NOT NULL )
		ORDER BY
			 pv.PKG_ID,
			 pv.PV_ID,
			 pd.DPKG_ID,
			 pd.DPV_ID;
	EXCEPTION
		WHEN OTHERS THEN
			dbms_output.put_line('AllIssues exception: ' || SQLERRM );
	END;


	-- NOTE: make RM_PACKAGE_ISSUES a temporary table when tested ok

	/*
	-- Proc: LoadIssuesTable
	--
	-- Populates Package_Issues table with details of issues from all dependent packages.
	-- This will be for all package versions of the input pkg_name between the
	-- version_start and version_end.
	--
	-- INPUT PARAMETERS:
	--
	--		pkg_name  	-  	The name of the top level package to get issues for
	--		version_start	-	The start version for the comparison
	--		version_end	-	The end version for the comparison
	*/
	PROCEDURE LoadIssuesTable( vCursor OUT T_Cur, pkg_name IN VARCHAR2, version_start IN VARCHAR2, version_end IN VARCHAR2 )
	AS
		pkgId	NUMBER;

		CURSOR pack_vers_cur IS
			SELECT
				pv.PV_ID,
				pv.PKG_VERSION,
				pv.PKG_ID,
				p.PKG_NAME
			FROM
				PACKAGE_VERSIONS pv
					JOIN PACKAGES p ON pv.PKG_ID = p.PKG_ID
			WHERE
   				 pv.PKG_ID = pkgId
			AND
				VersionIsBetween( pv.PKG_VERSION, version_start, version_end ) = 1;

	BEGIN
		DELETE FROM RELEASE_MANAGER.RM_PKG_ISSUES; /*RM_PACKAGE_ISSUES replaced by RM_PKG_ISSUES*/

		-- get the pkg_id we are finding issues for
		pkgId := GetPkgId( pkg_name );

		-- find all the top level packages we are dealing with and recursively process their issues and their dependent package issues.
		FOR pack_ver_rec IN  pack_vers_cur
		LOOP
			InsertIssuesForDepends( pack_ver_rec.PV_ID, pack_ver_rec.PKG_ID, pack_ver_rec.PKG_NAME, pack_ver_rec.PV_ID, pack_ver_rec.PKG_VERSION );
			COMMIT;
		END LOOP;

		-- The output cursor - shows the individual versions of the top level package then were reported on
		OPEN vCursor FOR
		SELECT DISTINCT ISS_ID, PKG_VERSION FROM RM_PKG_ISSUES WHERE ISS_ID IS NOT NULL; /*RM_PACKAGE_ISSUES replaced by RM_PKG_ISSUES*/
/*removed
		SELECT
			PKG_VERSION
		FROM
			RELEASE_MANAGER.RM_PACKAGE_ISSUES;
*/


	EXCEPTION
		WHEN OTHERS THEN
			dbms_output.put_line('LoadIssuesTable exception: ' || SQLERRM );
	END;


	/*
	-- Proc: InsertIssuesForDepends
	--
	-- Used by LoadIssuesTable to recursively find issues for all dependent packages
	--
	-- INPUT PARAMETERS:
	--
	--		pvID  		-  	The package version id of the package to get issues for
	--		top_pkgID	-  	The package id of the top level package to get issues for - should be the same as pvID when called from LoadIssuesTable (different when called recursively)
	--		top_pkgName -  	The package name of the top level package
	--		top_pvID  	-  	The package version id of the top level package
	--		top_pkgVer  -  	The package version description of the top level package
	*/
	PROCEDURE InsertIssuesForDepends( pvID IN NUMBER, top_pkgID IN NUMBER, top_pkgName IN VARCHAR2, top_pvID IN NUMBER, top_pkgVer IN VARCHAR2 )
	AS
		pkgId		NUMBER;
		issCnt		NUMBER := 0;
		pkgCheck	NUMBER := 0;
		depCheck	NUMBER := 0;

		dpkgName	VARCHAR(50);
		dpkgVersion	VARCHAR(50);

		CURSOR dep_packs_cur IS
			SELECT
				DPV_ID
			FROM
				PACKAGE_DEPENDENCIES
			WHERE
				PV_ID = pvID;

	BEGIN

		-- check to see if the package has been processed previously
		SELECT
			COUNT(*)
		INTO
			pkgCheck
		FROM
			RM_PKG_ISSUES /*RM_PACKAGE_ISSUES replaced by RM_PKG_ISSUES*/
		WHERE
			DPV_ID = pvID;

		dbms_output.put_line('pkgCheck: ' || pkgCheck );

		-- Package not already processed (no cyclic dependency) - process it
		IF ( pkgCheck = 0 ) THEN

			-- check to see if this package version has any issues assigned to it
			SELECT
				COUNT(*)
			INTO
				issCnt
			FROM
				CQ_ISSUES i
			WHERE
				i.PV_ID = pvID;

			dbms_output.put_line('issCnt: ' || issCnt );

			-- Always enter a marker row into the table even if there are no issues for the package.
			-- This allows us to pick up any cyclic dependencies.
			IF ( issCnt > 0 ) THEN
				-- get issues and insert into RM_PACKAGE_ISSUES
				/*RM_PACKAGE_ISSUES replaced by RM_PKG_ISSUES*/

				INSERT INTO RM_PKG_ISSUES ( PKG_ID, PKG_NAME, PV_ID, PKG_VERSION, DPV_ID, DPKG_NAME, DPKG_VERSION, ISS_DB, ISS_ID )
					SELECT DISTINCT
						top_pkgID		AS PKG_ID,
						top_pkgName		AS PKG_NAME,
						top_pvID		AS PV_ID,
						top_pkgVer		AS PKG_VERSION,
						pv.PV_ID		AS DPV_ID,
						p.PKG_NAME		AS DPKG_NAME,
						pv.PKG_VERSION	AS DPKG_VERSION,
						ci.ISS_DB,
						ci.ISS_ID
					FROM
						PACKAGE_VERSIONS pv
							JOIN PACKAGES p ON pv.PKG_ID = p.PKG_ID
							JOIN CQ_ISSUES ci ON pv.PV_ID = ci.PV_ID
					WHERE
						pv.PV_ID = pvID;

			ELSE
				-- get the dpkg details - there will always be a row returned here
				SELECT
					p.PKG_NAME
				INTO
					dpkgName
				FROM
					PACKAGE_VERSIONS pv
						JOIN PACKAGES p ON pv.PKG_ID = p.PKG_ID
				WHERE
	   				 pv.PV_ID = pvID;

				SELECT
					pv.PKG_VERSION
				INTO
					dpkgVersion
				FROM
					PACKAGE_VERSIONS pv
				WHERE
	   				 pv.PV_ID = pvID;

				-- enter a marker row
				/*RM_PACKAGE_ISSUES replaced by RM_PKG_ISSUES*/
				INSERT INTO RM_PKG_ISSUES ( PKG_ID, PKG_NAME, PV_ID, PKG_VERSION, DPV_ID, DPKG_NAME, DPKG_VERSION, ISS_DB, ISS_ID )
				VALUES (
					top_pkgID,
					top_pkgName,
					top_pvID,
					top_pkgVer,
					pvID,
					dpkgName,
					dpkgVersion,
					NULL,
					NULL );

			END IF;

			-- If this package version has dependencies then recurse
			SELECT
				COUNT(*)
			INTO
				depCheck
			FROM
				PACKAGE_DEPENDENCIES
			WHERE
				PV_ID = pvID;

			IF ( depCheck > 0 ) THEN
				-- get dependencies and call this function recursively for each one
				FOR dep_rec IN  dep_packs_cur
				LOOP
					InsertIssuesForDepends( dep_rec.DPV_ID, top_pkgID, top_pkgName, top_pvID, top_pkgVer );
				END LOOP;

			END IF;

		END IF;

	/*EXCEPTION
		WHEN OTHERS THEN
			no exception handling required
	*/
	END;

END Rm_Issues;

/
--------------------------------------------------------
--  DDL for Function CAN_EDIT_PKG_IN_PROJECT
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "RELEASE_MANAGER"."CAN_EDIT_PKG_IN_PROJECT" ( nPvId IN NUMBER, nRtagId IN NUMBER ) RETURN NUMBER IS
-- Returns 0 : Package is not editable in this Release
--         1 : Package is editable in this release
/* ---------------------------------------------------------------------------
    Version: 3.0.0
   --------------------------------------------------------------------------- */

  VExt PACKAGE_VERSIONS.V_EXT%TYPE;
  ProjId NUMBER;
  RowCount NUMBER;
  cReleaseMode CHAR(1);

BEGIN

  /*--------------- Business Rules Here -------------------*/
  IF (nRtagId IS NULL)  OR  (nRtagId < 1)THEN
    RETURN 0;
  END IF;
  /*-------------------------------------------------------*/

  /*-- First Check. See if package is used through release reference --*/
  SELECT COUNT(rc.PV_ID) INTO RowCount
    FROM (
        SELECT rl.REF_RTAG_ID
        FROM RELEASE_LINKS rl
       WHERE rl.RTAG_ID = nRtagId
        ) rl,
      RELEASE_CONTENT rc
    WHERE rc.RTAG_ID = rl.REF_RTAG_ID
      AND rc.PV_ID = nPvId;

  -- Decide if package can be edited
  IF RowCount > 0 THEN
    -- Package is referenced from other release, hence cannot be edited
    RETURN 0;
  END IF;

-- Check if the package is included through an SDK reference
  SELECT count(*) INTO RowCount
    FROM RELEASE_CONTENT rc
   WHERE rc.RTAG_ID = nRtagId
      AND rc.PV_ID = nPvId
      AND rc.SDKTAG_ID is not NULL ;

  IF RowCount > 0 THEN
    -- Package is imported via SDK
    RETURN 0;
  END IF;

--  Pegged packages can be edited. Other checking needs to be done
--  -- Check if the package is pegged
--  SELECT count(*) INTO RowCount
--    FROM pegged_versions
--   WHERE RTAG_ID = nRtagId
--      AND PV_ID = nPvId;

--  IF RowCount > 0 THEN
--    -- Package is Pegged
--    RETURN 0;
--  END IF;

  -- Check is only done for releases in restrictive mode
  SELECT rt.OFFICIAL INTO cReleaseMode
    FROM RELEASE_TAGS rt
   WHERE rt.RTAG_ID = nRtagId;

  IF cReleaseMode = 'N' OR cReleaseMode = 'R'  OR cReleaseMode = 'C' THEN
    -- Do not do any further checking,
    -- Package is editable here
    RETURN 1;
  END IF;


  /*-- Further checking --*/
  -- Get proj_id
  SELECT rt.PROJ_ID  INTO  ProjId
    FROM RELEASE_TAGS rt
   WHERE rt.RTAG_ID = nRtagId;

  BEGIN
    -- Get v_ext
    SELECT pv.V_EXT  INTO  Vext
      FROM PACKAGE_VERSIONS pv
     WHERE pv.PV_ID = nPvId;

    EXCEPTION
        WHEN NO_DATA_FOUND THEN
            Vext := NULL;
  END;

  --Temp Hack for Step Project
  IF ProjId != 281 THEN
    -- Find if package can be edited in this project
      SELECT COUNT(pe.EXT_NAME) INTO RowCount
      FROM PROJECT_EXTENTIONS pe
      WHERE pe.PROJ_ID != ProjId
        AND pe.EXT_NAME = VExt;
  END IF;

  -- Decide if package can be edited
  IF RowCount > 0 THEN
    -- Package extension is found in other projects, hence NOT EDITABLE
    RETURN 0;
  ELSE
    RETURN 1;
  END IF;


END CAN_EDIT_PKG_IN_PROJECT;

/
--------------------------------------------------------
--  DDL for Function DT_ADDUSEROBJECT
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "RELEASE_MANAGER"."DT_ADDUSEROBJECT" RETURN NUMBER IS NEWOBJECTID NUMBER; BEGIN /* GET THE NEXT VALUE FROM THE SEQUENCE FOR THE OBJECT ID */ SELECT MICROSOFTSEQDTPROPERTIES.NEXTVAL INTO NEWOBJECTID FROM DUAL; /* ADD THE PARENT NODE FOR THE NEW OBJECT */ INSERT INTO MICROSOFTDTPROPERTIES ( ID, OBJECTID, PROPERTY ) VALUES ( NEWOBJECTID, NEWOBJECTID, 'DtgSchemaOBJECT' ); RETURN( NEWOBJECTID ); END DT_ADDUSEROBJECT;

/
--------------------------------------------------------
--  DDL for Function GET_AUTOMATED_LABEL
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "RELEASE_MANAGER"."GET_AUTOMATED_LABEL" ( nPvId IN NUMBER ) RETURN VARCHAR2 IS

/* ---------------------------------------------------------------------------
    Version: 3.0.0
   --------------------------------------------------------------------------- */

  sPkgName VARCHAR2(4000);
  sPkgVersion VARCHAR2(4000);
  sVext VARCHAR2(4000);
  cChangeType CHAR;
  cBuildType CHAR;


BEGIN

	-- Get package details
	SELECT pkg.PKG_NAME, pv.V_EXT, pv.build_type, pv.change_type, pv.pkg_version INTO sPkgName, sVext,cBuildType, cChangeType, sPkgVersion
	  FROM PACKAGE_VERSIONS pv,
	  	   PACKAGES pkg
	 WHERE pv.PKG_ID = pkg.PKG_ID
	   AND pv.PV_ID = nPvId;

  -- Generate Label for manually built package
  If cBuildType = 'M' Then
    return (sPkgName ||'_'|| sPkgVersion );
  End If;

  -- Generate Label for automated build with specified package version
  IF cchangetype = 'F' Then
    return (sPkgName ||'_'|| sPkgVersion ||'.WIP');
  End If;

	-- Generate Label for automated build
	RETURN UPPER( sPkgName ||'.'|| nPvId || sVext ||'.WIP' );

END GET_AUTOMATED_LABEL;

/
--------------------------------------------------------
--  DDL for Function GET_BUILD_NUMBER
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "RELEASE_MANAGER"."GET_BUILD_NUMBER" (s_version IN VARCHAR2) RETURN VARCHAR2
IS
/* ---------------------------------------------------------------------------
    Version: 1.0.0
   --------------------------------------------------------------------------- */
BEGIN
    IF is_number(s_version) AND LENGTH(s_version) > 3
    THEN
        RETURN MOD(TO_NUMBER(s_version), 1000);
    ELSE
        RETURN 0;
    END IF;
END get_build_number;

/
--------------------------------------------------------
--  DDL for Function GET_PATCH_VERSION
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "RELEASE_MANAGER"."GET_PATCH_VERSION" (s_version IN VARCHAR2) RETURN VARCHAR2
IS
/* ---------------------------------------------------------------------------
    Version: 1.0.0
   --------------------------------------------------------------------------- */
BEGIN
    IF is_number(s_version) AND LENGTH(s_version) > 3
    THEN
        RETURN FLOOR(TO_NUMBER(s_version) / 1000);
    ELSE
        RETURN s_version;
    END IF;
END get_patch_version;

/
--------------------------------------------------------
--  DDL for Function GET_PV_FIRST_MODIFIED
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "RELEASE_MANAGER"."GET_PV_FIRST_MODIFIED" (v_pv_id NUMBER) RETURN DATE IS
  ret DATE;
BEGIN
  SELECT q.modified_stamp
    INTO ret
    FROM (
            SELECT level AS lvl, pvc.pv_id, pvc.modified_stamp, pvc.change_type
              FROM package_versions pvc
              START WITH pvc.pv_id = v_pv_id
            CONNECT BY NOCYCLE pvc.pv_id = PRIOR pvc.last_pv_id
          ) Q
  WHERE q.change_type IS NOT NULL
    AND rownum = 1
  ORDER BY q.lvl;

  RETURN ret;
END;

/

  GRANT EXECUTE ON "RELEASE_MANAGER"."GET_PV_FIRST_MODIFIED" TO "RM_READONLY";
  GRANT EXECUTE ON "RELEASE_MANAGER"."GET_PV_FIRST_MODIFIED" TO "DM_READONLY";
  GRANT EXECUTE ON "RELEASE_MANAGER"."GET_PV_FIRST_MODIFIED" TO "DEPLOYMENT_MANAGER";
--------------------------------------------------------
--  DDL for Function GET_V_EXT
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "RELEASE_MANAGER"."GET_V_EXT" (SSpkg_version IN PACKAGE_VERSIONS.pkg_version%TYPE) RETURN VARCHAR2 IS

/* ---------------------------------------------------------------------------
    Version: 3.0.0
   --------------------------------------------------------------------------- */

    SSV_EXT PACKAGE_VERSIONS.V_EXT%TYPE;
    lastDot NUMBER;

BEGIN
    lastDot := INSTR (SSpkg_version, '.', -1);

    IF ( lastDot > 0 ) AND ( lastDot != LENGTH(SSpkg_version) )
    THEN
        -- YES dot separator found --
        SSV_EXT := SUBSTR (SSpkg_version, lastDot, LENGTH(SSpkg_version)-lastDot+1);

        IF IS_VERSION_EXTENSION ( SSV_EXT )
        THEN
            RETURN SSV_EXT;
        ELSE
            RETURN NULL;
        END IF;

    ELSE
        -- NO dot separator found --
        RETURN NULL;
    END IF;

END GET_V_EXT;

/
--------------------------------------------------------
--  DDL for Function IN_LIST_NUMBER
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "RELEASE_MANAGER"."IN_LIST_NUMBER" ( sInList IN VARCHAR2 ) RETURN RELMGR_NUMBER_TAB_t IS

/* ---------------------------------------------------------------------------
    Version: 3.0.0
   --------------------------------------------------------------------------- */

    sync_rtags		   RELMGR_NUMBER_TAB_t := RELMGR_NUMBER_TAB_t();
	pos				   NUMBER;
	in_list			   VARCHAR2(4000) := sInList || ',';

BEGIN

	IF NOT sInList IS NULL
	THEN
		LOOP
	        EXIT WHEN in_list IS NULL;
	        pos := INSTR ( in_list, ',' );
	        sync_rtags.extend;
	        sync_rtags(sync_rtags.count) := LTRIM ( RTRIM ( SUBSTR ( in_list, 1, pos-1 ) ) );
	        in_list := SUBSTR ( in_list, pos+1 );
		END LOOP;
	END IF;

	RETURN sync_rtags;
END IN_LIST_NUMBER;

/
--------------------------------------------------------
--  DDL for Function IN_LIST_NUMBER2
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "RELEASE_MANAGER"."IN_LIST_NUMBER2" ( sInList IN VARCHAR2 ) RETURN RELMGR_NUMBER_TAB_t IS

/* ---------------------------------------------------------------------------
    Version: 3.0.0
   --------------------------------------------------------------------------- */

    sync_rtags		   RELMGR_NUMBER_TAB_t := RELMGR_NUMBER_TAB_t();
	pos				   NUMBER;
	in_list			   VARCHAR2(32767) := sInList || ',';

BEGIN

	IF NOT sInList IS NULL
	THEN
		LOOP
	        EXIT WHEN in_list IS NULL;
	        pos := INSTR ( in_list, ',' );
	        sync_rtags.extend;
	        sync_rtags(sync_rtags.count) := LTRIM ( RTRIM ( SUBSTR ( in_list, 1, pos-1 ) ) );
	        in_list := SUBSTR ( in_list, pos+1 );
		END LOOP;
	END IF;

	RETURN sync_rtags;
END IN_LIST_NUMBER2;

/
--------------------------------------------------------
--  DDL for Function IN_LIST_VARCHAR2
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "RELEASE_MANAGER"."IN_LIST_VARCHAR2" ( sInList IN VARCHAR2, cSeparator IN VARCHAR2 ) RETURN RELMGR_VARCHAR2_TAB_t IS

/* ---------------------------------------------------------------------------
    Version: 3.1
   --------------------------------------------------------------------------- */

    cItemCollection	   RELMGR_VARCHAR2_TAB_t := RELMGR_VARCHAR2_TAB_t();
	pos				   NUMBER;
	in_list			   VARCHAR2(4000) := sInList || cSeparator;
	val				   VARCHAR2(4000);

BEGIN

	IF NOT sInList IS NULL
	THEN
		LOOP
	        EXIT WHEN in_list IS NULL;
	        pos := INSTR ( in_list, cSeparator );
			val := LTRIM ( RTRIM ( SUBSTR ( in_list, 1, pos-1 ) ) );

			IF (NOT val IS NULL) THEN
		        cItemCollection.extend;
		        cItemCollection(cItemCollection.count) := val;
			END IF;

	        in_list := SUBSTR ( in_list, pos+1 );
		END LOOP;
	END IF;

	RETURN cItemCollection;
END IN_LIST_VARCHAR2;

/
--------------------------------------------------------
--  DDL for Function IS_NUMBER
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "RELEASE_MANAGER"."IS_NUMBER" (p_val IN VARCHAR2) RETURN BOOLEAN
IS
   temp_num NUMBER;
/* ---------------------------------------------------------------------------
    Version: 1.0.0
   --------------------------------------------------------------------------- */
BEGIN
   temp_num := TO_NUMBER(p_val);
   RETURN true;
EXCEPTION WHEN VALUE_ERROR THEN
   RETURN false;
END IS_NUMBER;

/
--------------------------------------------------------
--  DDL for Function IS_VERSION_EXTENSION
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "RELEASE_MANAGER"."IS_VERSION_EXTENSION" (SSV_EXT PACKAGE_VERSIONS.V_EXT%TYPE) RETURN BOOLEAN
IS
/* ---------------------------------------------------------------------------
    Version: 3.0.0
   --------------------------------------------------------------------------- */

BEGIN
    IF LENGTH ( TRIM (TRANSLATE (SSV_EXT, '.ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',' ') ) ) > 0
    THEN
        RETURN FALSE;
    ELSE
        RETURN TRUE;
    END IF;

END IS_VERSION_EXTENSION;

/
--------------------------------------------------------
--  DDL for Function ORA_SYSDATE
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "RELEASE_MANAGER"."ORA_SYSDATE" 
RETURN DATE
IS
/* ---------------------------------------------------------------------------
    Version: 3.0.0
   --------------------------------------------------------------------------- */
BEGIN

    RETURN TO_DATE( TO_CHAR( SYSDATE,'DD-MON-YYYY' ),'DD-MON-YYYY' );
END ORA_SYSDATE;

/
--------------------------------------------------------
--  DDL for Function ORA_SYSDATETIME
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "RELEASE_MANAGER"."ORA_SYSDATETIME" 
RETURN DATE
IS
/* ---------------------------------------------------------------------------
    Version: 3.0.0
   --------------------------------------------------------------------------- */
BEGIN

    RETURN TO_DATE( TO_CHAR( SYSDATE,'DD-MON-YYYY HH24:MI:SS' ),'DD-MON-YYYY HH24:MI:SS' );
END ORA_SYSDATETIME;

/
--------------------------------------------------------
--  DDL for Function PERL_DBD_TESTFUNC
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "RELEASE_MANAGER"."PERL_DBD_TESTFUNC" (a in integer, b in integer) return integer is c integer; begin if b is null then c := 0; else c := b; end if; return a * c + 1; end;

/
--------------------------------------------------------
--  DDL for Function RELEASE_MODE
--------------------------------------------------------

  CREATE OR REPLACE FUNCTION "RELEASE_MANAGER"."RELEASE_MODE" ( nRtagId IN NUMBER ) RETURN CHAR IS

/* ---------------------------------------------------------------------------
    Version: 3.0.0
   --------------------------------------------------------------------------- */

   returnValue CHAR(1);

BEGIN

    /*--------------- Business Rules Here -------------------*/
	/*-------------------------------------------------------*/

	-- Get release mode
	SELECT rt.OFFICIAL INTO returnValue
	  FROM RELEASE_TAGS rt
	 WHERE rt.RTAG_ID = nRtagId;

	RETURN returnValue;

END RELEASE_MODE;

/
--------------------------------------------------------
--  DDL for Synonymn APPLICATIONS
--------------------------------------------------------

  CREATE OR REPLACE SYNONYM "RELEASE_MANAGER"."APPLICATIONS" FOR "ACCESS_MANAGER"."APPLICATIONS";
--------------------------------------------------------
--  DDL for Synonymn APPLICATION_PAGES
--------------------------------------------------------

  CREATE OR REPLACE SYNONYM "RELEASE_MANAGER"."APPLICATION_PAGES" FOR "ACCESS_MANAGER"."APPLICATION_PAGES";
--------------------------------------------------------
--  DDL for Synonymn CONTROL_OBJECTS
--------------------------------------------------------

  CREATE OR REPLACE SYNONYM "RELEASE_MANAGER"."CONTROL_OBJECTS" FOR "ACCESS_MANAGER"."CONTROL_OBJECTS";
--------------------------------------------------------
--  DDL for Synonymn DATA_PERMISSIONS
--------------------------------------------------------

  CREATE OR REPLACE SYNONYM "RELEASE_MANAGER"."DATA_PERMISSIONS" FOR "ACCESS_MANAGER"."DATA_PERMISSIONS";
--------------------------------------------------------
--  DDL for Synonymn DATA_TABLES
--------------------------------------------------------

  CREATE OR REPLACE SYNONYM "RELEASE_MANAGER"."DATA_TABLES" FOR "ACCESS_MANAGER"."DATA_TABLES";
--------------------------------------------------------
--  DDL for Synonymn PAGE_CONTROL_OBJECTS
--------------------------------------------------------

  CREATE OR REPLACE SYNONYM "RELEASE_MANAGER"."PAGE_CONTROL_OBJECTS" FOR "ACCESS_MANAGER"."PAGE_CONTROL_OBJECTS";
--------------------------------------------------------
--  DDL for Synonymn PERMISSION_TYPES
--------------------------------------------------------

  CREATE OR REPLACE SYNONYM "RELEASE_MANAGER"."PERMISSION_TYPES" FOR "ACCESS_MANAGER"."PERMISSION_TYPES";
--------------------------------------------------------
--  DDL for Synonymn PK_AMUTILS
--------------------------------------------------------

  CREATE OR REPLACE SYNONYM "RELEASE_MANAGER"."PK_AMUTILS" FOR "ACCESS_MANAGER"."PK_AMUTILS";
--------------------------------------------------------
--  DDL for Synonymn PK_SECURITY
--------------------------------------------------------

  CREATE OR REPLACE SYNONYM "RELEASE_MANAGER"."PK_SECURITY" FOR "ACCESS_MANAGER"."PK_SECURITY";
--------------------------------------------------------
--  DDL for Synonymn ROLES
--------------------------------------------------------

  CREATE OR REPLACE SYNONYM "RELEASE_MANAGER"."ROLES" FOR "ACCESS_MANAGER"."ROLES";
--------------------------------------------------------
--  DDL for Synonymn ROLE_PRIVILEGES
--------------------------------------------------------

  CREATE OR REPLACE SYNONYM "RELEASE_MANAGER"."ROLE_PRIVILEGES" FOR "ACCESS_MANAGER"."ROLE_PRIVILEGES";
--------------------------------------------------------
--  DDL for Synonymn USERS
--------------------------------------------------------

  CREATE OR REPLACE SYNONYM "RELEASE_MANAGER"."USERS" FOR "ACCESS_MANAGER"."USERS";
--------------------------------------------------------
--  DDL for Synonymn USER_APPLICATIONS
--------------------------------------------------------

  CREATE OR REPLACE SYNONYM "RELEASE_MANAGER"."USER_APPLICATIONS" FOR "ACCESS_MANAGER"."USER_APPLICATIONS";
--------------------------------------------------------
--  DDL for Synonymn USER_ROLES
--------------------------------------------------------

  CREATE OR REPLACE SYNONYM "RELEASE_MANAGER"."USER_ROLES" FOR "ACCESS_MANAGER"."USER_ROLES";
--------------------------------------------------------
--  Constraints for Table PACKAGE_DOCUMENTS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_DOCUMENTS" MODIFY ("DOC_NUM" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_DOCUMENTS" MODIFY ("DOC_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_DOCUMENTS" MODIFY ("PV_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table RELEASE_METRICS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."RELEASE_METRICS" ADD CONSTRAINT "UNQ_RELEASE_METRICS" UNIQUE ("RTAG_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."RELEASE_METRICS" MODIFY ("RTAG_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table RELEASE_COMPONENTS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."RELEASE_COMPONENTS" MODIFY ("PV_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table BUILD_PLATFORMS_CONFIG
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."BUILD_PLATFORMS_CONFIG" MODIFY ("GBE_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."BUILD_PLATFORMS_CONFIG" MODIFY ("BP_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table PLANNED
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PLANNED" ADD CONSTRAINT "UNIQUE_PV_RTAG" UNIQUE ("PV_ID", "RTAG_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 131072 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."PLANNED" MODIFY ("VIEW_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PLANNED" MODIFY ("PV_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PLANNED" MODIFY ("RTAG_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table RELEASE_MODIFIED
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."RELEASE_MODIFIED" ADD CONSTRAINT "RELEASE_MODIFIED_PK" PRIMARY KEY ("RTAG_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."RELEASE_MODIFIED" MODIFY ("RTAG_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table PACKAGE_METRICS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_METRICS" ADD CONSTRAINT "UNQ_PACKAGE_METRICS" UNIQUE ("PV_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 4194304 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_METRICS" MODIFY ("PV_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table PROCESSES
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PROCESSES" ADD CONSTRAINT "PROCESSES_PK" PRIMARY KEY ("PROC_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."PROCESSES" MODIFY ("PROC_NAME" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PROCESSES" MODIFY ("PROC_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table PROJECT_ACTION_LOG
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PROJECT_ACTION_LOG" MODIFY ("ACTTYPE_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PROJECT_ACTION_LOG" MODIFY ("PROJ_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PROJECT_ACTION_LOG" MODIFY ("ACTION_DATETIME" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PROJECT_ACTION_LOG" MODIFY ("USER_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table ARCHIVE_ACTION_LOG
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."ARCHIVE_ACTION_LOG" MODIFY ("DESCRIPTION" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."ARCHIVE_ACTION_LOG" MODIFY ("RTAG_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."ARCHIVE_ACTION_LOG" MODIFY ("DATE_TIME_STAMP" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."ARCHIVE_ACTION_LOG" MODIFY ("USER_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table VTREES
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."VTREES" ADD CONSTRAINT "PK_VTREES" PRIMARY KEY ("VTREE_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."VTREES" MODIFY ("HIDE" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."VTREES" MODIFY ("VTREE_NAME" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."VTREES" MODIFY ("PROJ_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."VTREES" MODIFY ("VTREE_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table BUILD_INSTANCE_PLATFORMS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."BUILD_INSTANCE_PLATFORMS" MODIFY ("BP_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."BUILD_INSTANCE_PLATFORMS" MODIFY ("BUILD_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table PACKAGES
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PACKAGES" ADD CONSTRAINT "PK_PACKAGES" PRIMARY KEY ("PKG_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 131072 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."PACKAGES" MODIFY ("PKG_NAME" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PACKAGES" MODIFY ("PKG_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table IGNORE_WARNINGS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."IGNORE_WARNINGS" MODIFY ("DPV_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."IGNORE_WARNINGS" MODIFY ("PV_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."IGNORE_WARNINGS" MODIFY ("RTAG_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table PRODUCT_STATES
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PRODUCT_STATES" ADD CONSTRAINT "PRODUCT_STATES_PK" PRIMARY KEY ("STATE_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."PRODUCT_STATES" MODIFY ("STATE" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PRODUCT_STATES" MODIFY ("STATE_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table CODE_REVIEWS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."CODE_REVIEWS" MODIFY ("PV_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table WORLDS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."WORLDS" ADD CONSTRAINT "PK_WORLDS" PRIMARY KEY ("WORLD_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 131072 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."WORLDS" MODIFY ("WORLD_NAME" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."WORLDS" MODIFY ("WORLD_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table BUILD_INSTANCES
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."BUILD_INSTANCES" ADD CONSTRAINT "BUILD_ID" PRIMARY KEY ("BUILD_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."BUILD_INSTANCES" MODIFY ("STATE" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."BUILD_INSTANCES" MODIFY ("TIMESTAMP" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."BUILD_INSTANCES" MODIFY ("PV_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."BUILD_INSTANCES" MODIFY ("BUILD_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table BLAT_RELEASES
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."BLAT_RELEASES" MODIFY ("RTAG_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."BLAT_RELEASES" MODIFY ("BLAT_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table NOTE_MANAGER
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."NOTE_MANAGER" ADD CONSTRAINT "PKNOTE_MANAGER1" PRIMARY KEY ("NID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 131072 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."NOTE_MANAGER" MODIFY ("NID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table DAEMON_ACTION_LOG
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."DAEMON_ACTION_LOG" MODIFY ("RCON_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."DAEMON_ACTION_LOG" MODIFY ("USER_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table BUILD_MACHINES
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."BUILD_MACHINES" ADD CONSTRAINT "BUILD_MACHINES_PK" PRIMARY KEY ("BM_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."BUILD_MACHINES" MODIFY ("BM_NAME" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."BUILD_MACHINES" MODIFY ("BM_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table PLATFORMS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PLATFORMS" MODIFY ("NAME" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PLATFORMS" MODIFY ("CODE" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table VALIDATION_RULES_DELETE_ME
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."VALIDATION_RULES_DELETE_ME" MODIFY ("IS_REQUIRED" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."VALIDATION_RULES_DELETE_ME" MODIFY ("FIELD_NAME" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table PACKAGE_PROCESSES
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_PROCESSES" MODIFY ("PROC_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_PROCESSES" MODIFY ("PV_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table BUILD_PLAN
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."BUILD_PLAN" ADD CONSTRAINT "BUILD_PLAN_PK" PRIMARY KEY ("RTAG_ID", "BUILD_ORDER", "PV_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
--------------------------------------------------------
--  Constraints for Table MESSAGE_BOARD
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."MESSAGE_BOARD" ADD CONSTRAINT "PK_MESSAGE_BOARD" PRIMARY KEY ("MSG_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."MESSAGE_BOARD" MODIFY ("SUBMITION_DATE" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."MESSAGE_BOARD" MODIFY ("MSG_DETAILS" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."MESSAGE_BOARD" MODIFY ("MSG_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table VCS_TYPE
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."VCS_TYPE" ADD CONSTRAINT "VCS_TYPE_PK" PRIMARY KEY ("VCS_TYPE_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."VCS_TYPE" MODIFY ("TAG" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."VCS_TYPE" MODIFY ("NAME" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."VCS_TYPE" MODIFY ("VCS_TYPE_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table RUN_LEVEL
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."RUN_LEVEL" ADD CONSTRAINT "PK_RUN_LEVEL" PRIMARY KEY ("RCON_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."RUN_LEVEL" MODIFY ("RCON_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table LICENCES
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."LICENCES" ADD CONSTRAINT "PK_LICENCES" PRIMARY KEY ("LICENCE")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."LICENCES" MODIFY ("NAME" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."LICENCES" MODIFY ("LICENCE" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table UNIT_TESTS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."UNIT_TESTS" MODIFY ("TEST_TYPES_FK" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."UNIT_TESTS" MODIFY ("PV_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."UNIT_TESTS" MODIFY ("TEST_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table CQ_STATEDEF
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."CQ_STATEDEF" ADD CONSTRAINT "CQ_STATEDEF_PK" PRIMARY KEY ("ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."CQ_STATEDEF" MODIFY ("ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table TEMP_ENV_STATES
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."TEMP_ENV_STATES" MODIFY ("TES_STATE" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."TEMP_ENV_STATES" MODIFY ("PKG_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."TEMP_ENV_STATES" MODIFY ("PV_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."TEMP_ENV_STATES" MODIFY ("LEVEL_NUM" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."TEMP_ENV_STATES" MODIFY ("SESSION_NUM" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table TEMP_ENV_DEPS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."TEMP_ENV_DEPS" ADD CONSTRAINT "TEMP_ENV_DEPS_PK" PRIMARY KEY ("PV_ID", "SESSION_NUM", "DPV_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."TEMP_ENV_DEPS" MODIFY ("DPKG_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."TEMP_ENV_DEPS" MODIFY ("DPV_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."TEMP_ENV_DEPS" MODIFY ("PKG_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."TEMP_ENV_DEPS" MODIFY ("PV_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."TEMP_ENV_DEPS" MODIFY ("SESSION_NUM" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table SDK_NAMES
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."SDK_NAMES" ADD CONSTRAINT "SDK_NAMES_PK" PRIMARY KEY ("SDK_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."SDK_NAMES" ADD CONSTRAINT "SDK_NAMES_UK1" UNIQUE ("SDK_NAME")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."SDK_NAMES" MODIFY ("PROJ_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."SDK_NAMES" MODIFY ("VIEW_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."SDK_NAMES" MODIFY ("SDK_NAME" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."SDK_NAMES" MODIFY ("SDK_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table PROJECT_EXTENTIONS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PROJECT_EXTENTIONS" MODIFY ("EXT_NAME" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table PACKAGE_VERSIONS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_VERSIONS" ADD CONSTRAINT "PK_PACKAGE_VERSIONS" PRIMARY KEY ("PV_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 5242880 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_VERSIONS" MODIFY ("BUILD_TYPE" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_VERSIONS" MODIFY ("LAST_PV_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_VERSIONS" MODIFY ("OWNER_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_VERSIONS" MODIFY ("CREATOR_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_VERSIONS" MODIFY ("MODIFIER_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_VERSIONS" MODIFY ("DLOCKED" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_VERSIONS" MODIFY ("PKG_VERSION" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_VERSIONS" MODIFY ("PKG_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_VERSIONS" MODIFY ("PV_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table LXR_STATE
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."LXR_STATE" ADD CONSTRAINT "LXR_STATE_PK" PRIMARY KEY ("RTAG_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."LXR_STATE" MODIFY ("RTAG_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table BUILD_MACHINE_CONFIG
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."BUILD_MACHINE_CONFIG" ADD CONSTRAINT "PK_BUILD_MACHINE_CONFIG" PRIMARY KEY ("BMCON_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."BUILD_MACHINE_CONFIG" MODIFY ("ACTIVE" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."BUILD_MACHINE_CONFIG" MODIFY ("GBE_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."BUILD_MACHINE_CONFIG" MODIFY ("MACHINE_HOSTNAME" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."BUILD_MACHINE_CONFIG" MODIFY ("DISPLAY_NAME" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."BUILD_MACHINE_CONFIG" MODIFY ("BMCON_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table ADVISORY_RIPPLE
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."ADVISORY_RIPPLE" MODIFY ("PV_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."ADVISORY_RIPPLE" MODIFY ("RTAG_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table PACKAGE_DEPENDENCIES
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_DEPENDENCIES" MODIFY ("BUILD_TYPE" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_DEPENDENCIES" MODIFY ("DPKG_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_DEPENDENCIES" MODIFY ("PKG_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_DEPENDENCIES" MODIFY ("DPV_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_DEPENDENCIES" MODIFY ("PV_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table JIRA_ISSUES
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."JIRA_ISSUES" MODIFY ("PV_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table ADDITIONAL_NOTES
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."ADDITIONAL_NOTES" MODIFY ("MOD_USER" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."ADDITIONAL_NOTES" MODIFY ("MOD_DATE" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."ADDITIONAL_NOTES" MODIFY ("NOTE_TITLE" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."ADDITIONAL_NOTES" MODIFY ("PV_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."ADDITIONAL_NOTES" MODIFY ("NOTE_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table ARCHIVE_DATA
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."ARCHIVE_DATA" MODIFY ("PV_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."ARCHIVE_DATA" MODIFY ("RTAG_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table BUILD_ENVIRONMENTS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."BUILD_ENVIRONMENTS" ADD CONSTRAINT "PK_BUILD_ENVIRONMENTS" PRIMARY KEY ("BE_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 131072 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."BUILD_ENVIRONMENTS" MODIFY ("BE_NAME" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."BUILD_ENVIRONMENTS" MODIFY ("BE_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table RELEASE_TAGS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."RELEASE_TAGS" MODIFY ("PLAN_DROP" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."RELEASE_TAGS" MODIFY ("PLAN_THRESHOLD" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."RELEASE_TAGS" ADD CONSTRAINT "PK_RELEASE_TAGS" PRIMARY KEY ("RTAG_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."RELEASE_TAGS" MODIFY ("PROJ_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."RELEASE_TAGS" MODIFY ("PARENT_RTAG_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."RELEASE_TAGS" MODIFY ("REBUILD_STAMP" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."RELEASE_TAGS" MODIFY ("REBUILD_ENV" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."RELEASE_TAGS" MODIFY ("OFFICIAL" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."RELEASE_TAGS" MODIFY ("RTAG_NAME" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."RELEASE_TAGS" MODIFY ("RTAG_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table AUTOBUILD_FAILURE
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."AUTOBUILD_FAILURE" ADD PRIMARY KEY ("GROUP_EMAIL_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."AUTOBUILD_FAILURE" MODIFY ("GROUP_EMAIL_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table SDK_CONTENT
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."SDK_CONTENT" MODIFY ("SDKPKG_STATE" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."SDK_CONTENT" MODIFY ("PV_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."SDK_CONTENT" MODIFY ("SDKTAG_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table ACTION_TYPE
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."ACTION_TYPE" ADD CONSTRAINT "UNQ_ACTTYPE_ID" PRIMARY KEY ("ACTTYPE_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 131072 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."ACTION_TYPE" MODIFY ("NAME" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."ACTION_TYPE" MODIFY ("ACTTYPE_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table SDK_TAGS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."SDK_TAGS" ADD CONSTRAINT "SDK_TAGS_PK" PRIMARY KEY ("SDKTAG_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."SDK_TAGS" MODIFY ("SDK_STATE" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."SDK_TAGS" MODIFY ("RTAG_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."SDK_TAGS" MODIFY ("SDK_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."SDK_TAGS" MODIFY ("SDKTAG_NAME" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."SDK_TAGS" MODIFY ("SDKTAG_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table PACKAGE_BUILD_ENV
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_BUILD_ENV" MODIFY ("BE_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_BUILD_ENV" MODIFY ("PV_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table BUILD_SERVICE_CONFIG
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."BUILD_SERVICE_CONFIG" MODIFY ("CONFIG" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."BUILD_SERVICE_CONFIG" MODIFY ("SERVICE" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table PACKAGE_VERSION_PLATFORMS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_VERSION_PLATFORMS" MODIFY ("BP_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_VERSION_PLATFORMS" MODIFY ("PV_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table GBE_MACHTYPE
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."GBE_MACHTYPE" ADD PRIMARY KEY ("GBE_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."GBE_MACHTYPE" MODIFY ("BM_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."GBE_MACHTYPE" MODIFY ("GBE_VALUE" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."GBE_MACHTYPE" MODIFY ("GBE_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table PACKAGE_INTEREST
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_INTEREST" MODIFY ("USER_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_INTEREST" MODIFY ("PROJ_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_INTEREST" MODIFY ("PKG_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table PRODUCT_COMPONENTS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PRODUCT_COMPONENTS" MODIFY ("OS_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PRODUCT_COMPONENTS" MODIFY ("PV_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table TEST_TYPES
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."TEST_TYPES" ADD CONSTRAINT "PK_TEST_TYPES" PRIMARY KEY ("TEST_TYPE_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 131072 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."TEST_TYPES" MODIFY ("TEST_TYPE_NAME" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."TEST_TYPES" MODIFY ("TEST_TYPE_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table MICROSOFTDTPROPERTIES
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."MICROSOFTDTPROPERTIES" ADD CONSTRAINT "MICROSOFT_PK_DTPROPERTIES" PRIMARY KEY ("ID", "PROPERTY")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 131072 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."MICROSOFTDTPROPERTIES" MODIFY ("VERSION" CONSTRAINT "MICROSOFT_NN_VERSION" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."MICROSOFTDTPROPERTIES" MODIFY ("PROPERTY" CONSTRAINT "MICROSOFT_NN_PROPERTY" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."MICROSOFTDTPROPERTIES" MODIFY ("ID" CONSTRAINT "MICROSOFT_NN_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table RELEASE_CONTENT
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."RELEASE_CONTENT" MODIFY ("PKG_STATE" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."RELEASE_CONTENT" MODIFY ("INSERTOR_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."RELEASE_CONTENT" MODIFY ("INSERT_STAMP" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."RELEASE_CONTENT" MODIFY ("BASE_VIEW_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."RELEASE_CONTENT" MODIFY ("PV_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."RELEASE_CONTENT" MODIFY ("RTAG_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table PEGGED_VERSIONS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PEGGED_VERSIONS" MODIFY ("PV_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PEGGED_VERSIONS" MODIFY ("RTAG_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table ABT_ACTION_LOG
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."ABT_ACTION_LOG" MODIFY ("RCON_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table LICENCING
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."LICENCING" ADD CONSTRAINT "LICENCING_PK" PRIMARY KEY ("PV_ID", "LICENCE")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."LICENCING" MODIFY ("LICENCE" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."LICENCING" MODIFY ("PV_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table DASH_BOARD
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."DASH_BOARD" MODIFY ("TOTAL_PACKAGES" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."DASH_BOARD" MODIFY ("AUTOMATED_PACKAGES" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."DASH_BOARD" MODIFY ("LAST_BUILD_TIME" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."DASH_BOARD" MODIFY ("RTAG_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."DASH_BOARD" MODIFY ("PROJ_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table BLAT_PROJECTS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."BLAT_PROJECTS" MODIFY ("PROJ_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."BLAT_PROJECTS" MODIFY ("BLAT_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table BUILD_PLATFORMS_CONFIG2
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."BUILD_PLATFORMS_CONFIG2" ADD CONSTRAINT "BUILD_PLATFORMS_CONFIG2_PK" PRIMARY KEY ("BP_ID", "BMCON_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_DATA"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."BUILD_PLATFORMS_CONFIG2" MODIFY ("BMCON_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."BUILD_PLATFORMS_CONFIG2" MODIFY ("BP_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table NOTIFICATION_HISTORY
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."NOTIFICATION_HISTORY" ADD CONSTRAINT "PK_NOTIFICATION_HISTORY" PRIMARY KEY ("RTAG_ID", "PV_ID", "USER_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 2097152 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."NOTIFICATION_HISTORY" MODIFY ("DATE_TIME_STAMP" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."NOTIFICATION_HISTORY" MODIFY ("USER_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."NOTIFICATION_HISTORY" MODIFY ("PV_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."NOTIFICATION_HISTORY" MODIFY ("RTAG_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table ACTION_LOG
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."ACTION_LOG" MODIFY ("ACTION_TIMESTAMP" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."ACTION_LOG" MODIFY ("ACTTYPE_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."ACTION_LOG" MODIFY ("PV_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."ACTION_LOG" MODIFY ("ACTION_DATETIME" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."ACTION_LOG" MODIFY ("USER_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table RELEASE_LINKS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."RELEASE_LINKS" MODIFY ("REF_RTAG_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."RELEASE_LINKS" MODIFY ("RTAG_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table VTREES_WORLD
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."VTREES_WORLD" MODIFY ("VTREE_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."VTREES_WORLD" MODIFY ("WORLD_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table BUILD_STANDARDS_ADDENDUM
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."BUILD_STANDARDS_ADDENDUM" ADD CONSTRAINT "BUILD_STANDARDS_ADDENDUM_PK" PRIMARY KEY ("BSA_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."BUILD_STANDARDS_ADDENDUM" MODIFY ("BS_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."BUILD_STANDARDS_ADDENDUM" MODIFY ("BSA_NAME" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."BUILD_STANDARDS_ADDENDUM" MODIFY ("BSA_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table WORK_IN_PROGRESS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."WORK_IN_PROGRESS" MODIFY ("VIEW_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."WORK_IN_PROGRESS" MODIFY ("PV_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."WORK_IN_PROGRESS" MODIFY ("RTAG_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table CQ_ISSUES
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."CQ_ISSUES" MODIFY ("MOD_DATE" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."CQ_ISSUES" MODIFY ("ISS_STATE" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."CQ_ISSUES" MODIFY ("ISS_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."CQ_ISSUES" MODIFY ("ISS_DB" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."CQ_ISSUES" MODIFY ("PV_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table BUILD_ORDER
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."BUILD_ORDER" MODIFY ("PV_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."BUILD_ORDER" MODIFY ("STEP_NUM" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."BUILD_ORDER" MODIFY ("RTAG_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table CODE_REVIEW_URL
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."CODE_REVIEW_URL" ADD CONSTRAINT "CODE_REVIEW_URL_PK" PRIMARY KEY ("CR_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 131072 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."CODE_REVIEW_URL" MODIFY ("DATE_OF_REVIEW" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."CODE_REVIEW_URL" MODIFY ("URL" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."CODE_REVIEW_URL" MODIFY ("PROJ_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."CODE_REVIEW_URL" MODIFY ("PV_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."CODE_REVIEW_URL" MODIFY ("CR_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table RELEASE_CONFIG
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."RELEASE_CONFIG" ADD PRIMARY KEY ("RCON_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."RELEASE_CONFIG" MODIFY ("RTAG_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."RELEASE_CONFIG" MODIFY ("RCON_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table PACKAGE_BUILD_INFO
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_BUILD_INFO" MODIFY ("BM_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_BUILD_INFO" MODIFY ("PV_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table VIEW_SETTINGS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."VIEW_SETTINGS" MODIFY ("VIEW_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."VIEW_SETTINGS" MODIFY ("USER_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table DEPRECATED_PACKAGES
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."DEPRECATED_PACKAGES" MODIFY ("COMMENTS" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."DEPRECATED_PACKAGES" MODIFY ("PKG_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."DEPRECATED_PACKAGES" MODIFY ("RTAG_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table DO_NOT_RIPPLE
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."DO_NOT_RIPPLE" MODIFY ("PV_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."DO_NOT_RIPPLE" MODIFY ("RTAG_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table CQ_SOFTWARE_ISSUE
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."CQ_SOFTWARE_ISSUE" ADD CONSTRAINT "CQ_SOFTWARE_ISSUE_PK" PRIMARY KEY ("DBID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."CQ_SOFTWARE_ISSUE" MODIFY ("DBID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table BLAT_SERVERS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."BLAT_SERVERS" ADD CONSTRAINT "BLAT_SERVERS_UK1" UNIQUE ("BLAT_SERVER_NAME")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_DATA"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."BLAT_SERVERS" ADD CONSTRAINT "BLAT_SERVERS_PK" PRIMARY KEY ("BLAT_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_DATA"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."BLAT_SERVERS" MODIFY ("BLAT_SEQNUM" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."BLAT_SERVERS" MODIFY ("BLAT_DISPLAY_NAME" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."BLAT_SERVERS" MODIFY ("BLAT_SERVER_NAME" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."BLAT_SERVERS" MODIFY ("BLAT_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table CQ_USERS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."CQ_USERS" ADD CONSTRAINT "CQ_USERS_PK" PRIMARY KEY ("DBID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."CQ_USERS" MODIFY ("DBID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table RUN_LEVEL_SCHEDULE
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."RUN_LEVEL_SCHEDULE" ADD PRIMARY KEY ("SCHEDULED_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 262144 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."RUN_LEVEL_SCHEDULE" MODIFY ("SCHEDULED_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table MEMBERS_GROUP
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."MEMBERS_GROUP" MODIFY ("GROUP_EMAIL_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table TEST_RUN
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."TEST_RUN" ADD CONSTRAINT "PK_TEST_RUN" PRIMARY KEY ("TESTRUN_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 109051904 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."TEST_RUN" MODIFY ("TEST_OUTCOME" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."TEST_RUN" MODIFY ("TEST_NAME" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."TEST_RUN" MODIFY ("TYPE" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."TEST_RUN" MODIFY ("PLATFORM" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."TEST_RUN" MODIFY ("BUILD_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."TEST_RUN" MODIFY ("TESTRUN_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table BUILD_STANDARDS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."BUILD_STANDARDS" ADD CONSTRAINT "BUILD_STANDARDS_PK" PRIMARY KEY ("BS_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."BUILD_STANDARDS" MODIFY ("BS_NAME" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."BUILD_STANDARDS" MODIFY ("BS_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table RUNTIME_DEPENDENCIES
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."RUNTIME_DEPENDENCIES" MODIFY ("MOD_USER" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."RUNTIME_DEPENDENCIES" MODIFY ("MOD_DATE" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."RUNTIME_DEPENDENCIES" MODIFY ("PV_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table DAEMON_INSTRUCTIONS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."DAEMON_INSTRUCTIONS" ADD CONSTRAINT "DAEMON_INSTRUCTIONS_UK1" UNIQUE ("OP_CODE", "RTAG_ID", "PV_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."DAEMON_INSTRUCTIONS" ADD CONSTRAINT "DAEMON_INSTRUCTIONS_PK" PRIMARY KEY ("DAEMON_INSTRUCTIONS_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."DAEMON_INSTRUCTIONS" MODIFY ("OP_CODE" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."DAEMON_INSTRUCTIONS" MODIFY ("DAEMON_INSTRUCTIONS_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table BUILD_ENV_DOCUMENTS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."BUILD_ENV_DOCUMENTS" MODIFY ("DOC_NUM" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."BUILD_ENV_DOCUMENTS" MODIFY ("BE_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table BUILD_PLATFORMS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."BUILD_PLATFORMS" ADD CONSTRAINT "BUILD_PLATFORMS_UK1" UNIQUE ("BP_NAME")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_DATA"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."BUILD_PLATFORMS" ADD CONSTRAINT "BUILD_PLATFORMS_PK" PRIMARY KEY ("BP_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_DATA"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."BUILD_PLATFORMS" MODIFY ("BP_ACTIVE" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."BUILD_PLATFORMS" MODIFY ("BP_NAME" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."BUILD_PLATFORMS" MODIFY ("BP_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table PACKAGE_PATCHES
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_PATCHES" MODIFY ("INSTALL_ORDER" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_PATCHES" MODIFY ("PATCH_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_PATCHES" MODIFY ("PV_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table PROJECTS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PROJECTS" ADD CONSTRAINT "PK_PROJECTS" PRIMARY KEY ("PROJ_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."PROJECTS" MODIFY ("PROJ_NAME" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."PROJECTS" MODIFY ("PROJ_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table VIEW_DEF
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."VIEW_DEF" MODIFY ("PKG_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."VIEW_DEF" MODIFY ("VIEW_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Constraints for Table VIEWS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."VIEWS" ADD CONSTRAINT "PK_VIEWS" PRIMARY KEY ("VIEW_ID")
  USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS 
  STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
  PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1
  BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
  TABLESPACE "RELEASE_MANAGER_INDX"  ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."VIEWS" MODIFY ("PUBLIC_READ" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."VIEWS" MODIFY ("BASE_VIEW" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."VIEWS" MODIFY ("OWNER_ID" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."VIEWS" MODIFY ("VIEW_NAME" NOT NULL ENABLE);
  ALTER TABLE "RELEASE_MANAGER"."VIEWS" MODIFY ("VIEW_ID" NOT NULL ENABLE);
--------------------------------------------------------
--  Ref Constraints for Table ABT_ACTION_LOG
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."ABT_ACTION_LOG" ADD FOREIGN KEY ("RCON_ID")
	  REFERENCES "RELEASE_MANAGER"."RELEASE_CONFIG" ("RCON_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table ACTION_LOG
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."ACTION_LOG" ADD CONSTRAINT "ACTION_LOG_FK1" FOREIGN KEY ("PV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ON DELETE CASCADE ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."ACTION_LOG" ADD CONSTRAINT "REFACTION_TYPE48" FOREIGN KEY ("ACTTYPE_ID")
	  REFERENCES "RELEASE_MANAGER"."ACTION_TYPE" ("ACTTYPE_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table ADDITIONAL_NOTES
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."ADDITIONAL_NOTES" ADD CONSTRAINT "FK_ADDITION_REF_PV_ID" FOREIGN KEY ("PV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table ADVISORY_RIPPLE
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."ADVISORY_RIPPLE" ADD FOREIGN KEY ("RTAG_ID")
	  REFERENCES "RELEASE_MANAGER"."RELEASE_TAGS" ("RTAG_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."ADVISORY_RIPPLE" ADD FOREIGN KEY ("PV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table AUTOBUILD_FAILURE
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."AUTOBUILD_FAILURE" ADD FOREIGN KEY ("PROJ_ID")
	  REFERENCES "RELEASE_MANAGER"."PROJECTS" ("PROJ_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."AUTOBUILD_FAILURE" ADD FOREIGN KEY ("VIEW_ID")
	  REFERENCES "RELEASE_MANAGER"."VIEWS" ("VIEW_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table BLAT_PROJECTS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."BLAT_PROJECTS" ADD CONSTRAINT "BLAT_PROJECTS_FK1" FOREIGN KEY ("BLAT_ID")
	  REFERENCES "RELEASE_MANAGER"."BLAT_SERVERS" ("BLAT_ID") ON DELETE CASCADE ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."BLAT_PROJECTS" ADD CONSTRAINT "BLAT_PROJECTS_FK2" FOREIGN KEY ("PROJ_ID")
	  REFERENCES "RELEASE_MANAGER"."PROJECTS" ("PROJ_ID") ON DELETE CASCADE ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table BLAT_RELEASES
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."BLAT_RELEASES" ADD CONSTRAINT "BLAT_RELEASES_FK1" FOREIGN KEY ("BLAT_ID")
	  REFERENCES "RELEASE_MANAGER"."BLAT_SERVERS" ("BLAT_ID") ON DELETE CASCADE ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."BLAT_RELEASES" ADD CONSTRAINT "BLAT_RELEASES_FK2" FOREIGN KEY ("RTAG_ID")
	  REFERENCES "RELEASE_MANAGER"."RELEASE_TAGS" ("RTAG_ID") ON DELETE CASCADE ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table BUILD_ENV_DOCUMENTS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."BUILD_ENV_DOCUMENTS" ADD CONSTRAINT "FK_BUILD_E_DOCS_REF_BUILD_ENV" FOREIGN KEY ("BE_ID")
	  REFERENCES "RELEASE_MANAGER"."BUILD_ENVIRONMENTS" ("BE_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table BUILD_INSTANCES
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."BUILD_INSTANCES" ADD CONSTRAINT "BUILD_INSTANCES_FK1" FOREIGN KEY ("RTAG_ID")
	  REFERENCES "RELEASE_MANAGER"."RELEASE_TAGS" ("RTAG_ID") ON DELETE SET NULL ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."BUILD_INSTANCES" ADD CONSTRAINT "BUILD_INSTANCES_FK2" FOREIGN KEY ("PV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ON DELETE CASCADE ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table BUILD_INSTANCE_PLATFORMS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."BUILD_INSTANCE_PLATFORMS" ADD CONSTRAINT "BUILD_INSTANCE_PLATFORMS_FK1" FOREIGN KEY ("BUILD_ID")
	  REFERENCES "RELEASE_MANAGER"."BUILD_INSTANCES" ("BUILD_ID") ON DELETE CASCADE ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."BUILD_INSTANCE_PLATFORMS" ADD CONSTRAINT "BUILD_INSTANCE_PLATFORMS_FK2" FOREIGN KEY ("BP_ID")
	  REFERENCES "RELEASE_MANAGER"."BUILD_PLATFORMS" ("BP_ID") ON DELETE CASCADE ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table BUILD_MACHINE_CONFIG
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."BUILD_MACHINE_CONFIG" ADD CONSTRAINT "FK_BM_GBE_ID" FOREIGN KEY ("GBE_ID")
	  REFERENCES "RELEASE_MANAGER"."GBE_MACHTYPE" ("GBE_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table BUILD_ORDER
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."BUILD_ORDER" ADD CONSTRAINT "FK_BO_PV_ID" FOREIGN KEY ("PV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."BUILD_ORDER" ADD CONSTRAINT "FK_BO_RTAG_ID" FOREIGN KEY ("RTAG_ID")
	  REFERENCES "RELEASE_MANAGER"."RELEASE_TAGS" ("RTAG_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table BUILD_PLAN
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."BUILD_PLAN" ADD CONSTRAINT "BUILD_PLAN_FK1" FOREIGN KEY ("PV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ON DELETE CASCADE ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."BUILD_PLAN" ADD CONSTRAINT "BUILD_PLAN_FK2" FOREIGN KEY ("RTAG_ID")
	  REFERENCES "RELEASE_MANAGER"."RELEASE_TAGS" ("RTAG_ID") ON DELETE CASCADE ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table BUILD_PLATFORMS_CONFIG
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."BUILD_PLATFORMS_CONFIG" ADD CONSTRAINT "BUILD_PLATFORMS_CONFIG_FK1" FOREIGN KEY ("BP_ID")
	  REFERENCES "RELEASE_MANAGER"."BUILD_PLATFORMS" ("BP_ID") ON DELETE CASCADE ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."BUILD_PLATFORMS_CONFIG" ADD CONSTRAINT "BUILD_PLATFORMS_CONFIG_FK2" FOREIGN KEY ("GBE_ID")
	  REFERENCES "RELEASE_MANAGER"."GBE_MACHTYPE" ("GBE_ID") ON DELETE CASCADE ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table BUILD_PLATFORMS_CONFIG2
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."BUILD_PLATFORMS_CONFIG2" ADD CONSTRAINT "TABLE1_FK1" FOREIGN KEY ("BP_ID")
	  REFERENCES "RELEASE_MANAGER"."BUILD_PLATFORMS" ("BP_ID") ON DELETE CASCADE ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."BUILD_PLATFORMS_CONFIG2" ADD CONSTRAINT "TABLE1_FK2" FOREIGN KEY ("BMCON_ID")
	  REFERENCES "RELEASE_MANAGER"."BUILD_MACHINE_CONFIG" ("BMCON_ID") ON DELETE CASCADE ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table BUILD_STANDARDS_ADDENDUM
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."BUILD_STANDARDS_ADDENDUM" ADD CONSTRAINT "BUILD_STANDARDS_ADDENDUM_R01" FOREIGN KEY ("BS_ID")
	  REFERENCES "RELEASE_MANAGER"."BUILD_STANDARDS" ("BS_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table CODE_REVIEWS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."CODE_REVIEWS" ADD CONSTRAINT "FK_CODE_REV_REF_PV_ID" FOREIGN KEY ("PV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table CODE_REVIEW_URL
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."CODE_REVIEW_URL" ADD CONSTRAINT "CODE_REVIEW_URL_PACKAGE_V_FK1" FOREIGN KEY ("PV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."CODE_REVIEW_URL" ADD CONSTRAINT "CODE_REVIEW_URL_PROJECT_V_FK1" FOREIGN KEY ("PROJ_ID")
	  REFERENCES "RELEASE_MANAGER"."PROJECTS" ("PROJ_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table CQ_ISSUES
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."CQ_ISSUES" ADD CONSTRAINT "FK_CQ_PV_ID" FOREIGN KEY ("PV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table DAEMON_ACTION_LOG
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."DAEMON_ACTION_LOG" ADD FOREIGN KEY ("RCON_ID")
	  REFERENCES "RELEASE_MANAGER"."RELEASE_CONFIG" ("RCON_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."DAEMON_ACTION_LOG" ADD FOREIGN KEY ("ACTTYPE_ID")
	  REFERENCES "RELEASE_MANAGER"."ACTION_TYPE" ("ACTTYPE_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table DAEMON_INSTRUCTIONS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."DAEMON_INSTRUCTIONS" ADD CONSTRAINT "DAEMON_INSTRUCTIONS_PV_ID_FK" FOREIGN KEY ("PV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."DAEMON_INSTRUCTIONS" ADD CONSTRAINT "DAEMON_INSTRUCTIONS_RTAG_ID_FK" FOREIGN KEY ("RTAG_ID")
	  REFERENCES "RELEASE_MANAGER"."RELEASE_TAGS" ("RTAG_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table DASH_BOARD
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."DASH_BOARD" ADD FOREIGN KEY ("PROJ_ID")
	  REFERENCES "RELEASE_MANAGER"."PROJECTS" ("PROJ_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."DASH_BOARD" ADD FOREIGN KEY ("RTAG_ID")
	  REFERENCES "RELEASE_MANAGER"."RELEASE_TAGS" ("RTAG_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table DO_NOT_RIPPLE
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."DO_NOT_RIPPLE" ADD FOREIGN KEY ("PV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."DO_NOT_RIPPLE" ADD FOREIGN KEY ("RTAG_ID")
	  REFERENCES "RELEASE_MANAGER"."RELEASE_TAGS" ("RTAG_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table GBE_MACHTYPE
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."GBE_MACHTYPE" ADD CONSTRAINT "GBE_MACHTYPE_BUILD_MACHIN_FK1" FOREIGN KEY ("BM_ID")
	  REFERENCES "RELEASE_MANAGER"."BUILD_MACHINES" ("BM_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table IGNORE_WARNINGS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."IGNORE_WARNINGS" ADD CONSTRAINT "FK_IGW_DPV_ID" FOREIGN KEY ("DPV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."IGNORE_WARNINGS" ADD CONSTRAINT "FK_IGW_PV_ID" FOREIGN KEY ("PV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."IGNORE_WARNINGS" ADD CONSTRAINT "FK_IGW_RTAG_ID" FOREIGN KEY ("RTAG_ID")
	  REFERENCES "RELEASE_MANAGER"."RELEASE_TAGS" ("RTAG_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table JIRA_ISSUES
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."JIRA_ISSUES" ADD CONSTRAINT "FK_JIRA_PV_ID" FOREIGN KEY ("PV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table LICENCING
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."LICENCING" ADD FOREIGN KEY ("PV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."LICENCING" ADD FOREIGN KEY ("LICENCE")
	  REFERENCES "RELEASE_MANAGER"."LICENCES" ("LICENCE") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table LXR_STATE
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."LXR_STATE" ADD CONSTRAINT "LXR_STATE_FK1" FOREIGN KEY ("RTAG_ID")
	  REFERENCES "RELEASE_MANAGER"."RELEASE_TAGS" ("RTAG_ID") ON DELETE CASCADE ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table MEMBERS_GROUP
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."MEMBERS_GROUP" ADD FOREIGN KEY ("GROUP_EMAIL_ID")
	  REFERENCES "RELEASE_MANAGER"."AUTOBUILD_FAILURE" ("GROUP_EMAIL_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table NOTIFICATION_HISTORY
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."NOTIFICATION_HISTORY" ADD CONSTRAINT "FK_NH_RTAG_ID" FOREIGN KEY ("RTAG_ID")
	  REFERENCES "RELEASE_MANAGER"."RELEASE_TAGS" ("RTAG_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."NOTIFICATION_HISTORY" ADD CONSTRAINT "FK_NK_PV_ID" FOREIGN KEY ("PV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") DISABLE;
--------------------------------------------------------
--  Ref Constraints for Table PACKAGE_BUILD_ENV
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_BUILD_ENV" ADD CONSTRAINT "FK_PKG_BUILD_E_REF_BUILD_ENV" FOREIGN KEY ("BE_ID")
	  REFERENCES "RELEASE_MANAGER"."BUILD_ENVIRONMENTS" ("BE_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_BUILD_ENV" ADD CONSTRAINT "FK_PKG_BUILD_E_REF_PKG_VERSION" FOREIGN KEY ("PV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table PACKAGE_BUILD_INFO
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_BUILD_INFO" ADD CONSTRAINT "PACKAGE_BUILD_INFO_FK1" FOREIGN KEY ("BSA_ID")
	  REFERENCES "RELEASE_MANAGER"."BUILD_STANDARDS_ADDENDUM" ("BSA_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_BUILD_INFO" ADD FOREIGN KEY ("PV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_BUILD_INFO" ADD FOREIGN KEY ("BM_ID")
	  REFERENCES "RELEASE_MANAGER"."BUILD_MACHINES" ("BM_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table PACKAGE_DEPENDENCIES
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_DEPENDENCIES" ADD CONSTRAINT "PACKAGE_DEPENDENCIES_FK1" FOREIGN KEY ("PV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ON DELETE CASCADE ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_DEPENDENCIES" ADD CONSTRAINT "PACKAGE_DEPENDENCIES_FK2" FOREIGN KEY ("DPV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ON DELETE CASCADE ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_DEPENDENCIES" ADD CONSTRAINT "PACKAGE_DEPENDENCIES_FK3" FOREIGN KEY ("DPKG_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGES" ("PKG_ID") ON DELETE CASCADE ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_DEPENDENCIES" ADD CONSTRAINT "PACKAGE_DEPENDENCIES_FK4" FOREIGN KEY ("PKG_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGES" ("PKG_ID") ON DELETE CASCADE ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table PACKAGE_DOCUMENTS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_DOCUMENTS" ADD CONSTRAINT "FK_PKGDOCS_REF_PV" FOREIGN KEY ("PV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table PACKAGE_INTEREST
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_INTEREST" ADD FOREIGN KEY ("PROJ_ID")
	  REFERENCES "RELEASE_MANAGER"."PROJECTS" ("PROJ_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table PACKAGE_METRICS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_METRICS" ADD CONSTRAINT "FK_PACKAGE_METRICS_PV_ID" FOREIGN KEY ("PV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table PACKAGE_PATCHES
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_PATCHES" ADD CONSTRAINT "FK_PP_PATCH_ID" FOREIGN KEY ("PATCH_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_PATCHES" ADD CONSTRAINT "FK_PP_PV_ID" FOREIGN KEY ("PV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table PACKAGE_PROCESSES
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_PROCESSES" ADD CONSTRAINT "PACKAGE_PROCESSES_R01" FOREIGN KEY ("PV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_PROCESSES" ADD CONSTRAINT "PACKAGE_PROCESSES_R02" FOREIGN KEY ("PROC_ID")
	  REFERENCES "RELEASE_MANAGER"."PROCESSES" ("PROC_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table PACKAGE_VERSIONS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_VERSIONS" ADD CONSTRAINT "PACKAGE_VERSIONS_VCS_TYPE" FOREIGN KEY ("VCS_TYPE_ID")
	  REFERENCES "RELEASE_MANAGER"."VCS_TYPE" ("VCS_TYPE_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_VERSIONS" ADD CONSTRAINT "PKG_NAME_EXISTS" FOREIGN KEY ("PKG_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGES" ("PKG_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_VERSIONS" ADD FOREIGN KEY ("BS_ID")
	  REFERENCES "RELEASE_MANAGER"."BUILD_STANDARDS" ("BS_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table PACKAGE_VERSION_PLATFORMS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_VERSION_PLATFORMS" ADD CONSTRAINT "PACKAGE_VERSIONS_PLATFORM_FK1" FOREIGN KEY ("PV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ON DELETE CASCADE ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."PACKAGE_VERSION_PLATFORMS" ADD CONSTRAINT "PACKAGE_VERSION_PLATFORMS_FK1" FOREIGN KEY ("BP_ID")
	  REFERENCES "RELEASE_MANAGER"."BUILD_PLATFORMS" ("BP_ID") ON DELETE CASCADE ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table PEGGED_VERSIONS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PEGGED_VERSIONS" ADD CONSTRAINT "PEGGED_VERSIONS_PACKAG_FK1" FOREIGN KEY ("PV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."PEGGED_VERSIONS" ADD CONSTRAINT "PEGGED_VERSIONS_RELEAS_FK1" FOREIGN KEY ("RTAG_ID")
	  REFERENCES "RELEASE_MANAGER"."RELEASE_TAGS" ("RTAG_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table PLANNED
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PLANNED" ADD CONSTRAINT "REFPACKAGE_VERSIONS54" FOREIGN KEY ("PV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."PLANNED" ADD CONSTRAINT "REFRELEASE_TAGS53" FOREIGN KEY ("RTAG_ID")
	  REFERENCES "RELEASE_MANAGER"."RELEASE_TAGS" ("RTAG_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."PLANNED" ADD CONSTRAINT "REFVIEWS55" FOREIGN KEY ("VIEW_ID")
	  REFERENCES "RELEASE_MANAGER"."VIEWS" ("VIEW_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table PLANNED_VERSIONS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PLANNED_VERSIONS" ADD FOREIGN KEY ("PKG_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGES" ("PKG_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table PRODUCT_COMPONENTS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PRODUCT_COMPONENTS" ADD CONSTRAINT "REFPACKAGE_VERSIONS49" FOREIGN KEY ("PV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table PROJECT_ACTION_LOG
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."PROJECT_ACTION_LOG" ADD CONSTRAINT "REFACTION_TYPE63" FOREIGN KEY ("ACTTYPE_ID")
	  REFERENCES "RELEASE_MANAGER"."ACTION_TYPE" ("ACTTYPE_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."PROJECT_ACTION_LOG" ADD FOREIGN KEY ("RTAG_ID")
	  REFERENCES "RELEASE_MANAGER"."RELEASE_TAGS" ("RTAG_ID") DISABLE;
--------------------------------------------------------
--  Ref Constraints for Table RELEASE_COMPONENTS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."RELEASE_COMPONENTS" ADD CONSTRAINT "FK_RCONT_PV_ID" FOREIGN KEY ("PV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table RELEASE_CONFIG
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."RELEASE_CONFIG" ADD CONSTRAINT "RELEASE_CONFIG_FK1" FOREIGN KEY ("BMCON_ID")
	  REFERENCES "RELEASE_MANAGER"."BUILD_MACHINE_CONFIG" ("BMCON_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."RELEASE_CONFIG" ADD FOREIGN KEY ("RTAG_ID")
	  REFERENCES "RELEASE_MANAGER"."RELEASE_TAGS" ("RTAG_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table RELEASE_CONTENT
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."RELEASE_CONTENT" ADD CONSTRAINT "RELEASE_CONTENT_FK1" FOREIGN KEY ("SDKTAG_ID")
	  REFERENCES "RELEASE_MANAGER"."SDK_TAGS" ("SDKTAG_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."RELEASE_CONTENT" ADD FOREIGN KEY ("PKG_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGES" ("PKG_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."RELEASE_CONTENT" ADD FOREIGN KEY ("PRODUCT_STATE")
	  REFERENCES "RELEASE_MANAGER"."PRODUCT_STATES" ("STATE_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table RELEASE_LINKS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."RELEASE_LINKS" ADD CONSTRAINT "REFRELEASE_TAGS56" FOREIGN KEY ("RTAG_ID")
	  REFERENCES "RELEASE_MANAGER"."RELEASE_TAGS" ("RTAG_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."RELEASE_LINKS" ADD CONSTRAINT "REFRELEASE_TAGS58" FOREIGN KEY ("REF_RTAG_ID")
	  REFERENCES "RELEASE_MANAGER"."RELEASE_TAGS" ("RTAG_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table RELEASE_METRICS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."RELEASE_METRICS" ADD CONSTRAINT "FK_RELEASE_METRICS_RTAG_ID" FOREIGN KEY ("RTAG_ID")
	  REFERENCES "RELEASE_MANAGER"."RELEASE_TAGS" ("RTAG_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table RELEASE_MODIFIED
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."RELEASE_MODIFIED" ADD CONSTRAINT "RELEASE_MODIFIED_RELEASE__FK1" FOREIGN KEY ("RTAG_ID")
	  REFERENCES "RELEASE_MANAGER"."RELEASE_TAGS" ("RTAG_ID") ON DELETE CASCADE ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table RUNTIME_DEPENDENCIES
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."RUNTIME_DEPENDENCIES" ADD CONSTRAINT "FK_RTD_PV_ID" FOREIGN KEY ("PV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."RUNTIME_DEPENDENCIES" ADD CONSTRAINT "FK_RTD_RTD_ID" FOREIGN KEY ("RTD_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table RUN_LEVEL
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."RUN_LEVEL" ADD FOREIGN KEY ("RCON_ID")
	  REFERENCES "RELEASE_MANAGER"."RELEASE_CONFIG" ("RCON_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."RUN_LEVEL" ADD FOREIGN KEY ("CURRENT_PKG_ID_BEING_BUILT")
	  REFERENCES "RELEASE_MANAGER"."PACKAGES" ("PKG_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table SDK_CONTENT
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."SDK_CONTENT" ADD CONSTRAINT "SDK_CONTENT_FK1" FOREIGN KEY ("PV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."SDK_CONTENT" ADD CONSTRAINT "SDK_CONTENT_FK2" FOREIGN KEY ("SDKTAG_ID")
	  REFERENCES "RELEASE_MANAGER"."SDK_TAGS" ("SDKTAG_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table SDK_NAMES
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."SDK_NAMES" ADD CONSTRAINT "SDK_NAMES_FK1" FOREIGN KEY ("VIEW_ID")
	  REFERENCES "RELEASE_MANAGER"."VIEWS" ("VIEW_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."SDK_NAMES" ADD CONSTRAINT "SDK_NAMES_FK2" FOREIGN KEY ("PROJ_ID")
	  REFERENCES "RELEASE_MANAGER"."PROJECTS" ("PROJ_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table SDK_TAGS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."SDK_TAGS" ADD CONSTRAINT "SDK_TAGS_FK1" FOREIGN KEY ("SDK_ID")
	  REFERENCES "RELEASE_MANAGER"."SDK_NAMES" ("SDK_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."SDK_TAGS" ADD CONSTRAINT "SDK_TAGS_FK2" FOREIGN KEY ("RTAG_ID")
	  REFERENCES "RELEASE_MANAGER"."RELEASE_TAGS" ("RTAG_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table TEST_RUN
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."TEST_RUN" ADD CONSTRAINT "TEST_RUN_FK1" FOREIGN KEY ("BUILD_ID")
	  REFERENCES "RELEASE_MANAGER"."BUILD_INSTANCES" ("BUILD_ID") ON DELETE CASCADE ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table UNIT_TESTS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."UNIT_TESTS" ADD CONSTRAINT "FK_UT_REF_PV_ID" FOREIGN KEY ("PV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."UNIT_TESTS" ADD CONSTRAINT "FK_UT_REF_TEST_TYPES" FOREIGN KEY ("TEST_TYPES_FK")
	  REFERENCES "RELEASE_MANAGER"."TEST_TYPES" ("TEST_TYPE_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table VTREES_WORLD
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."VTREES_WORLD" ADD CONSTRAINT "FK_VW_REF_VTREE_ID" FOREIGN KEY ("VTREE_ID")
	  REFERENCES "RELEASE_MANAGER"."VTREES" ("VTREE_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."VTREES_WORLD" ADD CONSTRAINT "FK_VW_REF_WORLD_ID" FOREIGN KEY ("WORLD_ID")
	  REFERENCES "RELEASE_MANAGER"."WORLDS" ("WORLD_ID") ENABLE;
--------------------------------------------------------
--  Ref Constraints for Table WORK_IN_PROGRESS
--------------------------------------------------------

  ALTER TABLE "RELEASE_MANAGER"."WORK_IN_PROGRESS" ADD CONSTRAINT "REFPACKAGE_VERSIONS51" FOREIGN KEY ("PV_ID")
	  REFERENCES "RELEASE_MANAGER"."PACKAGE_VERSIONS" ("PV_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."WORK_IN_PROGRESS" ADD CONSTRAINT "REFRELEASE_TAGS50" FOREIGN KEY ("RTAG_ID")
	  REFERENCES "RELEASE_MANAGER"."RELEASE_TAGS" ("RTAG_ID") ENABLE;
  ALTER TABLE "RELEASE_MANAGER"."WORK_IN_PROGRESS" ADD CONSTRAINT "REFVIEWS52" FOREIGN KEY ("VIEW_ID")
	  REFERENCES "RELEASE_MANAGER"."VIEWS" ("VIEW_ID") ENABLE;
