--- lastchg-install.sql ---
--- version with sequence instead of timestamp:
-- lastchg_addto(TABLE,COLUMN,FILL)
--    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,text) returns text as '
declare
  tbl alias for $1;
  col alias for $2;
  fill alias for $3;
  trigfn text;
  trignm text;
  exec1  text;
  exec2  text;
  seq_name text;
begin
  trignm := ''_rserv'' || ''_'' || fill || ''_lctr'';
  trigfn := ''_rserv'' || ''_'' || fill || ''_lcup()'';
  seq_name := ''_rserv'' || ''_'' || fill || ''_seq_'';

  exec1 := ''create function '' || trigfn || '' returns opaque as '''' '' ||
                        ''begin '' ||
                        ''NEW.'' || col || '' = '' || ''OLD.'' || col || '' ; '' ||
                        ''return NEW; '' ||
                        ''end; '' ||
                        '' '''' language ''''plpgsql'''';'';
  exec2 := ''create trigger '' || trignm ||
                        '' before update on '' || tbl ||
                        '' for each row execute procedure '' || trigfn || '';'';
  execute exec1;
  execute exec2;

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



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

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

--- End of lastchg-install.sql ---

