--
-- group_contains_p/3
--
create or replace function group_contains_p(
  integer,
  integer,
  integer
) returns bool as $$

declare 
        group_contains_p__group_id        alias for $1;
        group_contains_p__component_id    alias for $2;
        group_contains_p__rel_id          alias for $3;
        map                               record;
begin
  if group_contains_p__group_id = group_contains_p__component_id then
    return 't';
  else
    if group_contains_p__rel_id is null then
      for map in  select *
                  from group_component_map
                  where component_id = group_contains_p__component_id
                  and group_id = container_id 
      LOOP
        if group_contains_p(group_contains_p__group_id, map.group_id, null) = 't' then
          return 't';
        end if;
      end loop;
    else
      for map in  select *
                  from group_component_map
                  where component_id = group_contains_p__component_id
                  and rel_id = group_contains_p__rel_id
                  and group_id = container_id 
      LOOP
        if group_contains_p(group_contains_p__group_id, map.group_id, null) = 't' then
          return 't';
        end if;
      end loop;
    end if;
    return 'f';
  end if;
end;$$ language plpgsql;