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

drop trigger if exists words__words__upd ON words;

create trigger words__words__upd after
update of words
   on
   words for each row execute procedure words__words__trg();

drop trigger if exists words__words__ins ON words;

create trigger words__words__ins after
insert
   on
   words for each row execute procedure words__words__trg();

drop trigger if exists ttw__f1__ins ON ttw;

create or replace function ttw__f1__trg()
returns trigger
language plpgsql
as
$$
begin
   delete from ttw__f1 where ttw__f1.parent__id = new.recid;

   return new;
end;
$$;

create trigger ttw__f1__ins after
insert
   on
   ttw for each row execute procedure ttw__f1__trg();

alter table words__words   drop constraint if exists pk__words__words;
alter table words__words   add constraint pk__words__words   primary key (parent__id, word);
drop index if exists idx__words__words;
create index idx__words__words on words__words (word);
alter table words__words   drop constraint if exists fk__words__words;
drop index if exists fkidx__words__words;
create index fkidx__words__words on words__words (parent__id);
alter table words__words
   add constraint fk__words__words
   foreign key (parent__id)
   references words(recid)
   on delete cascade;

alter table ttw__f1   drop constraint if exists pk__ttw__f1;
alter table ttw__f1   add constraint pk__ttw__f1   primary key (parent__id, list__index, word);
drop index if exists idx__ttw__f1;
create index idx__ttw__f1 on ttw__f1 (word);
alter table ttw__f1   drop constraint if exists fk__ttw__f1;
drop index if exists fkidx__ttw__f1;
create index fkidx__ttw__f1 on ttw__f1 (parent__id);
alter table ttw__f1
   add constraint fk__ttw__f1
   foreign key (parent__id)
   references ttw(recid)
   on delete cascade;

