CREATE LANGUAGE plpgsql;

CREATE OR REPLACE FUNCTION public.syncschema() RETURNS trigger AS '
DECLARE old_path TEXT;
BEGIN
  -- Save old search_path; notice we must qualify current_setting
  -- to ensure we invoke the right function
  old_path := pg_catalog.current_setting(''search_path'');
  -- Set a secure search_path: trusted schemas, then pg_temp.
  -- We set is_local = true so that the old value will be restored
  -- in event of an error before we reach the function end.
  PERFORM pg_catalog.set_config(''search_path'', ''postgres, pg_temp'', true);
  IF tg_op = ''INSERT'' THEN
    insert into postgres.sessions (session_id,display,uname,server,client,status,init_time,last_time,cookie,agent_pid,gr_port,sound_port,fs_port) values (new.session_id,new.display,new.uname,new.server,new.client,new.status,new.init_time,new.last_time,new.cookie,new.agent_pid,new.gr_port,new.sound_port,new.fs_port);
  ELSEIF tg_op = ''DELETE'' THEN
    delete from postgres.sessions where session_id=old.session_id;
  ELSEIF tg_op = ''UPDATE'' THEN
    update postgres.sessions set display=new.display,uname=new.uname,server=new.server,client=new.client,status=new.status,init_time=new.init_time,last_time=new.last_time,cookie=new.cookie,agent_pid=new.agent_pid,gr_port=new.gr_port,sound_port=new.sound_port,fs_port=new.fs_port where session_id=old.session_id;
  END IF;
  -- Restore the search_path of the caller
  PERFORM pg_catalog.set_config(''search_path'', old_path, true);
  RETURN NULL;
END ' LANGUAGE plpgsql SECURITY DEFINER;

 -- Add TRIGGER with a statement such as the following:
 -- CREATE TRIGGER syncschema AFTER INSERT OR DELETE OR UPDATE ON <schema name>.sessions FOR EACH ROW EXECUTE PROCEDURE public.syncschema();
