--
-- acs_sc_binding__new/2
--
create or replace function acs_sc_binding__new(
  integer,
  integer
) returns int4 as $$

declare
    p_contract_id		alias for $1;
    p_impl_id			alias for $2;
    v_contract_name		varchar;
    v_impl_name			varchar;
    v_count			integer;
begin

    v_contract_name := acs_sc_contract__get_name(p_contract_id);
    v_impl_name := acs_sc_impl__get_name(p_impl_id);

    select count(*) into v_count
    from acs_sc_operations
    where contract_id = p_contract_id
    and operation_name not in (select impl_operation_name
		       	       from acs_sc_impl_aliases
			       where impl_contract_name = v_contract_name
			       and impl_id = p_impl_id);

    if v_count > 0 then
        raise exception 'Binding of % to % failed since certain operations are not implemented.', v_contract_name, v_impl_name;
    end if;

    insert into acs_sc_bindings (
        contract_id,
	impl_id
    ) values (
        p_contract_id,
	p_impl_id
    );

    return 0;

end;$$ language plpgsql;


--
-- acs_sc_binding__new/2
--
create or replace function acs_sc_binding__new(
  character varying,
  character varying
) returns int4 as $$

declare
    p_contract_name		alias for $1;
    p_impl_name			alias for $2;
    v_contract_id		integer;
    v_impl_id			integer;
    v_count			integer;
begin

    v_contract_id := acs_sc_contract__get_id(p_contract_name);

    v_impl_id := acs_sc_impl__get_id(p_contract_name,p_impl_name);

    if v_contract_id is null or v_impl_id is null then
        raise exception 'Binding of % to % failed.', p_contract_name, p_impl_name;
    else
        perform acs_sc_binding__new(v_contract_id,v_impl_id);
    end if;

    return 0;

end;$$ language plpgsql;