Skip to content

Instantly share code, notes, and snippets.

@almightycouch
Last active August 16, 2019 07:56
Show Gist options
  • Save almightycouch/793fa17e74d43261b17f to your computer and use it in GitHub Desktop.
Save almightycouch/793fa17e74d43261b17f to your computer and use it in GitHub Desktop.
PostgreSQL changefeed using NOTIFY
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