create or replace
function lsmb__is_workday(in_date date, in_calendar integer)
returns boolean
language sql
as $$
select extract(isodow from $1) <= 5;
$$;
create table holidays (
calendar integer,
holidate date,
primary key (calendar, holidate)
);
create or replace
function lsmb__is_holiday(in_date date, in_calendar integer)
returns boolean
language plpgsql
as $$
begin
if exists(select *
from holidays
where holidate = in_date
and calendar = in_calendar) then
return true;
else
return false;
end if;
end;
$$;
create or replace
function lsmb__next_business_day(in_date date, in_calendar integer,
in_direction integer)
returns date
language plpgsql
as $$
declare
t_date date;
begin
t_date := in_date;
loop
exit when lsmb__is_workday(t_date, in_calendar)
and (not lsmb__is_holiday(t_date, in_calendar));
t_date := t_date + in_direction;
end loop;
return t_date;
end;
$$;
create or replace
function lsmb__next_business_day_modified(in_date date, in_calendar integer,
in_direction integer)
returns date
language plpgsql
as $$
declare
t_date date;
begin
select lsmb__next_business_day(in_date, in_calendar, in_direction)
into t_date;
if extract(month from in_date) != extract(month from t_date) then
select lsmb__next_business_day(in_date, in_calendar, -1 * in_direction)
into t_date;
end if;
return t_date;
end;
$$;
create or replace
function lsmb__closest_business_day(in_date date, in_calendar integer,
in_type integer)
returns date
language plpgsql
as $$
declare
t_date date;
begin
if in_type = 1 then -- no adjustment
t_date := in_date;
elseif in_type = 2 then -- following
select lsmb__next_business_day(in_date, in_calendar, 1)
into t_date;
elseif in_type = 3 then -- modified following
select lsmb__next_business_day_modified(in_date, in_calendar, 1)
into t_date;
elseif in_type = 4 then -- previous
select lsmb__next_businss_day(in_date, in_calendar, -1)
into t_date;
elseif in_type = 5 then -- modified previous
select lsmb__next_business_day_modified(in_date, in_calendar, -1)
into t_date;
else
raise
end if;
return t_date;
end;
$$;