CREATE SCHEMA timewarp;

CREATE OR REPLACE FUNCTION timewarp.yearperiod_fill_all()
    RETURNS  boolean
AS $BODY$
DECLARE    

BEGIN   

    PERFORM  timewarp.yearperiod_fill(yearperiod_id) FROM (
                    SELECT
                            yearperiod_id
                        FROM
                            public.yearperiod

                    ) x;
    RETURN true;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
  
ALTER FUNCTION   timewarp.yearperiod_fill_all()
  OWNER TO admin;
 


CREATE OR REPLACE FUNCTION timewarp.yearperiod_fill(integer)
    RETURNS  boolean

AS $BODY$
DECLARE
    i_yearperiod_id  ALIAS FOR $1;

    r_yearperiod RECORD;
    r_yearperiodview RECORD;

    v_is_update BOOLEAN;

BEGIN
    
    SELECT
            *
    INTO
        r_yearperiod
    FROM
        timewarp.yearperiod
    WHERE
        yearperiod_id = i_yearperiod_id;

    v_is_update := false;
    -- already there..
    IF FOUND THEN
        v_is_update := true;
    END IF;

    SELECT
        *
    INTO
        r_yearperiodview
    FROM
        timewarp.yearperiodview
    WHERE
        yearperiod_id = i_yearperiod_id;
    
    IF v_is_update THEN

        UPDATE
            timewarp.yearperiod
        SET 
            yearperiod_start   =  r_yearperiodview.yearperiod_start,
            yearperiod_end     =  r_yearperiodview.yearperiod_end,
            yearperiod_closed  =  r_yearperiodview.yearperiod_closed
             
        WHERE
            yearperiod_id = i_yearperiod_id;
    
    ELSE

        INSERT INTO  timewarp.yearperiod (
            yearperiod_id, yearperiod_start, 
            yearperiod_end, yearperiod_closed
        ) VALUES  (
            r_yearperiodview.yearperiod_id, r_yearperiodview.yearperiod_start,
            r_yearperiodview.yearperiod_end, r_yearperiodview.yearperiod_closed
        );
    END IF;
    
    RETURN true;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
  
ALTER FUNCTION  timewarp.yearperiod_fill(integer)
  OWNER TO admin;
  
SELECT timewarp.yearperiod_fill_all();  