-- lastchg_addto(TABLE,COLUMN)
--    Creates a "last changed" trigger on the indicated table/column
--    The column should be of type "timestamp" and is set to the current time 
--    whenever a row is inserted/updated.
--
create function lastchg_addto(text,text) returns text as '
declare
  tbl alias for $1;
  col alias for $2;
  trigfn text;
  trignm text;
  exec1  text;
  exec2  text;
begin
  trignm := tbl || ''_'' || col || ''_lctrig'';
  trigfn := tbl || ''_'' || col || ''_lcupdate()'';
  exec1 := ''create function '' || trigfn || '' returns opaque as '''' '' ||
			''begin '' ||
			''NEW.'' || col || '' = now(); '' ||
			''return NEW; '' ||
			''end; '' ||
			'' '''' language ''''plpgsql'''';'';
  exec2 := ''create trigger '' || trignm ||
			'' before insert or update on '' || tbl || 
			'' for each row execute procedure '' || trigfn || '';'';
  execute exec1;
  execute exec2;

  return ''Created lastchg trigger'';
end;
' language 'plpgsql';



-- lastchg_remove(TABLE,COLUMN)
--    Removes a "last changed" trigger on the indicated table/column
--
create function lastchg_remove(text,text) returns text as '
declare
  tbl alias for $1;
  col alias for $2;
  trigfn text;
  trignm text;
begin
  trignm := tbl || ''_'' || col || ''_lctrig'';
  trigfn := tbl || ''_'' || col || ''_lcupdate()'';
  execute ''drop trigger '' || trignm || '' on '' || tbl || '';'';
  execute ''drop function '' || trigfn || '';'';

  return ''Removed lastchg trigger'';
end;
' language 'plpgsql';
