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

declare
  check_context_index__object_id              alias for $1;  
  check_context_index__ancestor_id            alias for $2;  
  check_context_index__n_generations          alias for $3;  
  n_rows                                      integer;       
  n_gens                                      integer;       
begin
   -- Verify that this row exists in the index.
   if check_context_index__object_id is null or check_context_index__ancestor_id is null then
	raise exception 'object_id or ancestor_id is null in acs_object__check_context_index';
   end if;	
   select case when count(*) = 0 then 0 else 1 end into n_rows
   from acs_object_context_index
   where object_id = check_context_index__object_id
   and ancestor_id = check_context_index__ancestor_id;

   if n_rows = 1 then
     -- Verify that the count is correct.
     select n_generations into n_gens
     from acs_object_context_index
     where object_id = check_context_index__object_id
     and ancestor_id = check_context_index__ancestor_id;

     if n_gens != check_context_index__n_generations then
       PERFORM acs_log__error('acs_object.check_representation', 
                              'Ancestor ' ||
                     check_context_index__ancestor_id || ' of object ' || 
                     check_context_index__object_id ||
		     ' reports being generation ' || n_gens ||
		     ' when it is actually generation ' || 
                     check_context_index__n_generations ||
		     '.');
       return 'f';
     else
       return 't';
     end if;
   else
     PERFORM acs_log__error('acs_object.check_representation', 
                            'Ancestor ' ||
                            check_context_index__ancestor_id || 
                            ' of object ' || check_context_index__object_id 
                            || ' is missing an entry in acs_object_context_index.');
     return 'f';
   end if;
  
end;$$ language plpgsql;