CREATE OR REPLACE FUNCTION food600.semafor_vypni(
	ip_hod character varying,
	OUT op_hod character varying)
    RETURNS character varying
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE
AS $BODY$
DECLARE li_semafor integer default 0;
li_pocet integer default 0;
li_stav boolean ;
li integer default 0;

BEGIN
op_hod:='0';
select count(*) into li_pocet from food600.semafor where n_semafor=ip_hod;

IF li_pocet=0 THEN
	op_hod:='1'; 
ELSE
	select min(i_semafor) into li_semafor from food600.semafor where n_semafor=ip_hod;
	select pg_advisory_unlock(li_semafor) into li_stav;
	IF li_stav THEN
		op_hod:= '1';
	ELSE
		op_hod:= '0';
	END IF;
END IF;
if op_hod='1' then
	if food600.left(ip_hod,11)='KALKULACIA_' OR food600.left(ip_hod,14)='INTERNY_VYDAJ_' then
		delete from food600.semafor where n_semafor=ip_hod;
	end if;
end if;
END
$BODY$;
