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

declare
  check_index__group_id               alias for $1;  
  check_index__member_id              alias for $2;  
  check_index__container_id           alias for $3;  
  result                              boolean;       
  n_rows                              integer;       
  row                                 record;
begin

    select count(*) into n_rows
    from group_member_index
    where group_id = check_index__group_id
    and member_id = check_index__member_id
    and container_id = check_index__container_id;

    if n_rows = 0 then
      result := 'f';
      PERFORM acs_log__error('membership_rel.check_representation',
                    'Row missing from group_member_index: ' ||
                    'group_id = ' || check_index__group_id || ', ' ||
                    'member_id = ' || check_index__member_id || ', ' ||
                    'container_id = ' || check_index__container_id || '.');
    end if;

    for row in  select r.object_id_one as container_id
                from acs_rels r, composition_rels c
                where r.rel_id = c.rel_id
                and r.object_id_two = check_index__group_id  
    LOOP
      if membership_rel__check_index(row.container_id, check_index__member_id, check_index__container_id) = 'f' then
        result := 'f';
      end if;
    end loop;

    return result;
   
end;$$ language plpgsql;