create or replace function words (
      recid int8, txt text, toUpperCase boolean
   )
   returns table ( parent int8, word text ) language 'plpgsql' as
   $$
   declare arr text[];
   declare w text;
   begin
       arr = words(txt, toUpperCase);
       foreach w in array arr loop
           parent = recid;
           word = w;
           return next;
       end loop;
   end
   $$;

create or replace function ttwi_if1_trg()
returns trigger
language plpgsql
as
$$
begin
    delete from ttwi_if1 where ttwi_if1.parent__id = new.recid;
    insert into ttwi_if1 select * from words(new.recid, new.if1, true);
    return new;
end;
$$;

create trigger ttwi_if1_ins after
insert
    on
    ttwi for each row execute procedure ttwi_if1_trg();

create trigger ttwi_if1_upd after
update of if1
    on
    ttwi for each row execute procedure ttwi_if1_trg();

create or replace function ttwi_if2_trg()
returns trigger
language plpgsql
as
$$
begin
    delete from ttwi_if2 where ttwi_if2.parent__id = new.recid;
    insert into ttwi_if2 select * from words(new.recid, new.if2, false);
    return new;
end;
$$;

create trigger ttwi_if2_ins after
insert
    on
    ttwi for each row execute procedure ttwi_if2_trg();

create trigger ttwi_if2_upd after
update of if2
    on
    ttwi for each row execute procedure ttwi_if2_trg();

