--
-- content_type__register_relation_type/5
--
create or replace function content_type__register_relation_type(
  character varying,
  character varying,
  character varying,
  integer,
  integer
) returns int4 as $$

declare
  register_relation_type__content_type  alias for $1;  
  register_relation_type__target_type   alias for $2;  
  register_relation_type__relation_tag  alias for $3;  -- default 'generic'  
  register_relation_type__min_n         alias for $4;  -- default 0
  register_relation_type__max_n         alias for $5;  -- default null
  v_exists                              integer;       
begin

  -- check if the relation type exists
  select 
    count(*) into v_exists 
  from 
    cr_type_relations
  where 
    content_type = register_relation_type__content_type
  and
    target_type = register_relation_type__target_type
  and 
    relation_tag = register_relation_type__relation_tag;

  -- if the relation type does not exist, insert a row into cr_type_relations
  if v_exists = 0 then
    insert into cr_type_relations (
      content_type, target_type, relation_tag, min_n, max_n
    ) values (
      register_relation_type__content_type, 
      register_relation_type__target_type, 
      register_relation_type__relation_tag, 
      register_relation_type__min_n, register_relation_type__max_n
    );

  -- otherwise, update the row in cr_type_relations
  else
    update cr_type_relations set
      min_n = register_relation_type__min_n,
      max_n = register_relation_type__max_n
    where 
      content_type = register_relation_type__content_type
    and 
      target_type = register_relation_type__target_type
    and
      relation_tag = register_relation_type__relation_tag;
  end if;

  return 0; 
end;$$ language plpgsql;