Skip to content

Instantly share code, notes, and snippets.

@jmptrader
Forked from mminer/notify_event.sql
Created June 24, 2019 21:11
Show Gist options
  • Save jmptrader/cfb4d534597ee7166c6f714dc87b253b to your computer and use it in GitHub Desktop.
Save jmptrader/cfb4d534597ee7166c6f714dc87b253b to your computer and use it in GitHub Desktop.
PostgreSQL trigger function to send notifications when table changes.
-- Adapted from http://coussej.github.io/2015/09/15/Listening-to-generic-JSON-notifications-from-PostgreSQL-in-Go/
CREATE OR REPLACE FUNCTION notify_event() RETURNS TRIGGER AS $$
DECLARE
data JSON;
notification JSON;
BEGIN
-- Skip notification if row doesn't actually change in UPDATE.
-- We can accomplish the same thing with a WHERE clause in the CREATE TRIGGER statement,
-- but only if the trigger watches exclusively for UPDATE events.
IF TG_OP = 'UPDATE' AND OLD.* IS NOT DISTINCT FROM NEW.* THEN
RETURN NULL;
END IF;
IF TG_OP = 'DELETE' THEN
data = row_to_json(OLD);
ELSE
data = row_to_json(NEW);
END IF;
notification = json_build_object(
'table', TG_TABLE_NAME,
'action', TG_OP,
'row', data
);
PERFORM pg_notify('events', notification::text);
-- Result is ignored since we call this function in an AFTER trigger.
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
-- Using:
CREATE TRIGGER my_trigger
AFTER DELETE OR INSERT OR UPDATE ON my_table
FOR EACH ROW
EXECUTE PROCEDURE notify_event();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment