Last active
August 16, 2019 07:56
-
-
Save almightycouch/793fa17e74d43261b17f to your computer and use it in GitHub Desktop.
PostgreSQL changefeed using NOTIFY
This file contains 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
CREATE FUNCTION notify_changes() RETURNS trigger AS $$ | |
DECLARE | |
BEGIN | |
IF TG_OP = 'INSERT' THEN | |
PERFORM pg_notify('insert', json_build_object('table', TG_TABLE_NAME, 'new_val', row_to_json(NEW))#>>'{}'); | |
RETURN NEW; | |
ELSIF TG_OP = 'UPDATE' THEN | |
PERFORM pg_notify('update', json_build_object('table', TG_TABLE_NAME, 'new_val', row_to_json(NEW), 'old_val', row_to_json(OLD))#>>'{}'); | |
RETURN NEW; | |
ELSIF TG_OP = 'DELETE' THEN | |
PERFORM pg_notify('delete', json_build_object('table', TG_TABLE_NAME, 'old_val', row_to_json(old))#>>'{}'); | |
RETURN OLD; | |
END IF; | |
END; | |
$$ LANGUAGE plpgsql; | |
CREATE TRIGGER changefeed BEFORE INSERT OR UPDATE OR DELETE ON t | |
FOR EACH ROW EXECUTE PROCEDURE notify_changes(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment