--
-- timespan__join/2
--
create or replace function timespan__join(
  integer,
  integer
) returns int4 as $$
	-- time_intervals.interval_id%TYPE
declare
       join__timespan_1_id   alias for $1;
       join__timespan_2_id   alias for $2;
       v_interval_id	      time_intervals.interval_id%TYPE;
       rec_timespan	      record;
begin
       -- Loop over intervals in 2nd timespan, join with 1st.
       for rec_timespan in 
            select * 
            from   timespans
            where  timespan_id = join__timespan_2_id
       loop
            v_interval_id := timespan__join_interval(
			          join__timespan_1_id, 
				  rec_timespan.interval_id,
				  false
				  );
       end loop;

       -- JS: Return the last interval id joined.  Not very useful, since there may be
       -- JS: more than one interval joined
       return v_interval_id;

end;$$ language plpgsql;


--
-- timespan__join/3
--
create or replace function timespan__join(
  integer,
  timestamp with time zone,
  timestamp with time zone
) returns int4 as $$
	-- time_intervals.interval_id%TYPE
declare
       join__timespan_id   alias for $1;
       join__start_date    alias for $2; -- default null,
       join__end_date      alias for $3; -- default null
begin

       -- JS: This will create a new interval with start_date and end_date
       -- JS: so we might as well return the interval id 
       return timespan__join_interval(
		join__timespan_id, 
		time_interval__new(join__start_date, join__end_date),
		false
		);

end;$$ language plpgsql;