Skip to content

Instantly share code, notes, and snippets.

@MechanisM
Forked from bithavoc/postgres-notify-trigger.sql
Created February 13, 2018 02:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MechanisM/63ed7d0772b4c817110a07e962748ded to your computer and use it in GitHub Desktop.
Save MechanisM/63ed7d0772b4c817110a07e962748ded to your computer and use it in GitHub Desktop.
I used this trigger to notify table changes via NOTIFY (migrating off RethinkDB)
CREATE OR REPLACE FUNCTION notify_trigger() RETURNS trigger AS $$
DECLARE
channel_name varchar DEFAULT (TG_TABLE_NAME || '_changes');
BEGIN
IF TG_OP = 'INSERT' THEN
PERFORM pg_notify(channel_name, '{"id": "' || NEW.id || '"}');
RETURN NEW;
END IF;
IF TG_OP = 'DELETE' THEN
PERFORM pg_notify(channel_name, '{"id": "' || OLD.id || '"}');
RETURN OLD;
END IF;
IF TG_OP = 'UPDATE' THEN
PERFORM pg_notify(channel_name, '{"id": "' || NEW.id || '"}');
RETURN NEW;
END IF;
END;
$$ LANGUAGE plpgsql;
DROP TRIGGER IF EXISTS users_changes_trigger on users;
CREATE TRIGGER users_changes_trigger AFTER INSERT OR UPDATE OR DELETE ON users FOR EACH ROW EXECUTE PROCEDURE notify_trigger();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment