Skip to content

Instantly share code, notes, and snippets.

@SlyDen
Forked from bithavoc/postgres-notify-trigger.sql
Created February 16, 2017 15:03
Show Gist options
  • Save SlyDen/256b0c65dae7063c47a4a5f3ae49d663 to your computer and use it in GitHub Desktop.
Save SlyDen/256b0c65dae7063c47a4a5f3ae49d663 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