Skip to content

Instantly share code, notes, and snippets.

@mminer
Created September 18, 2018 19:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mminer/b0e12dafa735a21fe1470098203fdacc to your computer and use it in GitHub Desktop.
Save mminer/b0e12dafa735a21fe1470098203fdacc 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