--
-- on_lob_ref/0
--
create or replace function on_lob_ref(
  
) returns trigger as $$

begin
	if TG_OP = 'UPDATE' then
		if new.lob = old.lob then
			return new;
		end if;
	end if;

	if TG_OP = 'INSERT' or TG_OP = 'UPDATE' then
		if new.lob is not null then
			insert into lobs select new.lob, 0
				where 0 = (select count(*) from lobs where lob_id = new.lob);
			update lobs set refcount = refcount + 1 where lob_id = new.lob;
		end if;
	end if;

	if TG_OP <> 'INSERT' then
		if old.lob is not null then
			update lobs set refcount = refcount - 1 where lob_id = old.lob;
			delete from lobs where lob_id = old.lob and refcount = 0;
		end if;
	end if;

	if TG_OP = 'INSERT' or TG_OP = 'UPDATE' then return new;
	else return old;
	end if;

end;$$ language plpgsql;