Last active
June 25, 2016 16:03
-
-
Save ImTheDeveloper/7ec95e4f9770a3293b554137b1e98f2f to your computer and use it in GitHub Desktop.
Event emitter for postgresql listen function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Function: notify_event() | |
-- DROP FUNCTION notify_event(); | |
CREATE OR REPLACE FUNCTION notify_event() | |
RETURNS trigger AS | |
$BODY$ | |
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. | |
-- Execute pg_notify(channel, notification) | |
PERFORM pg_notify('events_'||TG_TABLE_NAME,'{"action":"'||TG_OP||'","data":'||data::text||'}'); | |
-- Result is ignored since this is an AFTER trigger | |
RETURN NULL; | |
END; | |
$BODY$ | |
LANGUAGE plpgsql VOLATILE | |
COST 100; | |
ALTER FUNCTION notify_event() | |
OWNER TO merlin; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Trigger: ally_target_notify_event on ally_target | |
-- DROP TRIGGER ally_target_notify_event ON ally_target; | |
CREATE TRIGGER ally_target_notify_event | |
AFTER INSERT OR UPDATE OR DELETE | |
ON ally_target | |
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