Skip to content

Instantly share code, notes, and snippets.

@jney
Last active December 22, 2015 21:58
Show Gist options
  • Save jney/6536483 to your computer and use it in GitHub Desktop.
Save jney/6536483 to your computer and use it in GitHub Desktop.
CREATE OR REPLACE FUNCTION notify_changes() RETURNS trigger AS $notify_changes$
DECLARE
CHANNEL TEXT;
ID TEXT;
JSON TEXT;
BEGIN
CHANNEL := 'changes';
IF (TG_OP = 'DELETE') THEN
ID := OLD.id;
ELSE
ID := NEW.id;
END IF;
JSON := '{"table_name":"' || TG_TABLE_NAME || '",' ||
'"operation":"' || TG_OP || '",' ||
'"id":"' || ID || '"}';
PERFORM pg_notify(CHANNEL, JSON);
RETURN NULL;
END;
$notify_changes$ LANGUAGE plpgsql;
DROP TRIGGER IF EXISTS notify_changes ON table_name;
CREATE TRIGGER notify_changes AFTER DELETE OR INSERT OR UPDATE ON table_name
FOR EACH ROW EXECUTE PROCEDURE notify_changes();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment