--
-- rel_constraint__violation_if_removed/1
--
create or replace function rel_constraint__violation_if_removed(
  integer
) returns varchar as $$

declare
  violation_if_removed__rel_id                 alias for $1;  
  v_count                                      integer;       
  v_error                                      text; 
  constraint_violated                          record;
begin
    v_error := null;

    select count(*) into v_count
      from dual
     where exists (select 1 
                     from rc_violations_by_removing_rel r 
                    where r.rel_id = violation_if_removed__rel_id);

    if v_count > 0 then
      -- some other relation depends on this one. Lets build up a string
      -- of the constraints we are violating
      for constraint_violated in select constraint_id, constraint_name
                                   from rc_violations_by_removing_rel r
                                  where r.rel_id = violation_if_removed__rel_id 
      LOOP

          v_error := v_error || 'Relational Constraint Violation: ' ||
                     constraint_violated.constraint_name || 
                     ' (constraint_id=' ||
                     constraint_violated.constraint_id || '). ';

      end loop;

    end if;

    return v_error;

   
end;$$ language plpgsql;