-- Deploy numerus:tag_relation to pg
-- requires: schema_numerus
-- requires: tag
-- requires: tag_name

begin;

set search_path to numerus, public;

create or replace function tag_relation(relname regclass, attname name, company integer, rowid integer, tags tag_name[]) returns void as
$$
begin
	execute format('delete from %I where %I = $1', relname, attname) USING rowid;
	
	if array_length(tags, 1) > 0 then
		insert into tag (company_id, name)
		select company, new_tag.name
		from unnest (tags) as new_tag(name)
		on conflict (company_id, name) do nothing
		;
	
		execute format('insert into %I (%I, tag_id) select $1, tag_id from tag join unnest ($2) as new_tag(name) on company_id = $3 and tag.name = new_tag.name', relname, attname) USING rowid, tags, company;
	end if;
end
$$
	language plpgsql;

revoke execute on function tag_relation(regclass, name, integer, integer, tag_name[]) from public;
grant execute on function tag_relation(regclass, name, integer, integer, tag_name[]) to invoicer;
grant execute on function tag_relation(regclass, name, integer, integer, tag_name[]) to admin;

commit;
