Skip to content

Instantly share code, notes, and snippets.

@josdirksen
Created October 4, 2015 17:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save josdirksen/24aec39b82bc722a40ca to your computer and use it in GitHub Desktop.
Save josdirksen/24aec39b82bc722a40ca to your computer and use it in GitHub Desktop.
--
CREATE OR REPLACE FUNCTION notify_event() RETURNS TRIGGER AS $$ DECLARE
data json;
notification json;
BEGIN
-- Convert the old or new row to JSON, based on the kind of action.
-- Action = DELETE? -> OLD row
-- Action = INSERT or UPDATE? -> NEW row
IF (TG_OP = 'DELETE') THEN
data = row_to_json(OLD);
ELSE
data = row_to_json(NEW);
END IF;
-- Contruct the notification as a JSON string.
notification = json_build_object(
'table',TG_TABLE_NAME,
'action', TG_OP,
'data', data);
-- Execute pg_notify(channel, notification)
PERFORM pg_notify('events',notification::text);
-- Result is ignored since this is an AFTER trigger
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
---
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment