--
-- API Package Body for Seqfeature_Source.
--
-- Scaffold auto-generated by gen-api.pl (H.Lapp, 2002).
--
-- $Id: Seqfeature_Source.pkb,v 1.1.1.1 2002-08-13 19:51:10 lapp Exp $
--

--
-- Copyright 2002-2003 Genomics Institute of the Novartis Research Foundation
-- Copyright 2002-2008 Hilmar Lapp
-- 
--  This file is part of BioSQL.
--
--  BioSQL is free software: you can redistribute it and/or modify it
--  under the terms of the GNU Lesser General Public License as
--  published by the Free Software Foundation, either version 3 of the
--  License, or (at your option) any later version.
--
--  BioSQL is distributed in the hope that it will be useful,
--  but WITHOUT ANY WARRANTY; without even the implied warranty of
--  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
--  GNU Lesser General Public License for more details.
--
--  You should have received a copy of the GNU Lesser General Public License
--  along with BioSQL. If not, see <http://www.gnu.org/licenses/>.
--

CREATE OR REPLACE
PACKAGE BODY FSrc IS

CURSOR FSrc_c (
		FSrc_NAME	IN SG_SEQFEATURE_SOURCE.NAME%TYPE)
RETURN SG_SEQFEATURE_SOURCE%ROWTYPE IS
	SELECT t.* FROM SG_SEQFEATURE_SOURCE t
	WHERE
		t.NAME = FSrc_NAME
	;

FUNCTION get_oid(
		FSrc_OID	IN SG_SEQFEATURE_SOURCE.OID%TYPE DEFAULT NULL,
		FSrc_NAME	IN SG_SEQFEATURE_SOURCE.NAME%TYPE,
		do_DML		IN NUMBER DEFAULT BSStd.DML_NO)
RETURN SG_SEQFEATURE_SOURCE.OID%TYPE
IS
	pk	SG_SEQFEATURE_SOURCE.OID%TYPE DEFAULT NULL;
	FSrc_row FSrc_c%ROWTYPE;
	--;
BEGIN
	-- initialize
	IF (do_DML > BSStd.DML_NO) THEN
		pk := FSrc_OID;
	END IF;
	-- look up
	IF pk IS NULL THEN
		FOR FSrc_row IN FSrc_c(FSrc_NAME) LOOP
		        pk := FSrc_row.OID;
		END LOOP;
	END IF;
	-- insert/update if requested
	IF (pk IS NULL) AND 
	   ((do_DML = BSStd.DML_I) OR (do_DML = BSStd.DML_UI)) THEN
	    	--
	    	-- insert the record and obtain the primary key
	    	pk := do_insert(
		        NAME => FSrc_NAME);
	ELSIF (do_DML = BSStd.DML_U) OR (do_DML = BSStd.DML_UI) THEN
	        -- update the record (note that not provided FKs will not
		-- be changed nor looked up)
		do_update(
			FSrc_OID	=> pk,
		        FSrc_NAME => FSrc_NAME);
	END IF;
	-- return the primary key
	RETURN pk;
END;

FUNCTION do_insert(
		NAME	IN SG_SEQFEATURE_SOURCE.NAME%TYPE)
RETURN SG_SEQFEATURE_SOURCE.OID%TYPE 
IS
	pk	SG_SEQFEATURE_SOURCE.OID%TYPE;
BEGIN
	-- pre-generate the primary key value
	SELECT SG_Sequence.nextval INTO pk FROM DUAL;
	-- insert the record
	INSERT INTO SG_SEQFEATURE_SOURCE (
		OID,
		NAME)
	VALUES (pk,
		NAME)
	;
	-- return the new pk value
	RETURN pk;
END;

PROCEDURE do_update(
		FSrc_OID	IN SG_SEQFEATURE_SOURCE.OID%TYPE,
		FSrc_NAME	IN SG_SEQFEATURE_SOURCE.NAME%TYPE)
IS
BEGIN
	-- update the record (and leave attributes passed as NULL untouched)
	UPDATE SG_SEQFEATURE_SOURCE
	SET
		NAME = NVL(FSrc_NAME, NAME)
	WHERE OID = FSrc_OID
	;
END;

END FSrc;
/

