Skip to content

Instantly share code, notes, and snippets.

@bithavoc
Last active August 15, 2024 15:15
Show Gist options
  • Save bithavoc/f40bbc33b553f2fddf9e1095858acdff to your computer and use it in GitHub Desktop.
Save bithavoc/f40bbc33b553f2fddf9e1095858acdff to your computer and use it in GitHub Desktop.
I used this trigger to notify table changes via NOTIFY (migrating off RethinkDB)
CREATE OR REPLACE FUNCTION notify_trigger() RETURNS trigger AS $$
DECLARE
channel_name varchar DEFAULT (TG_TABLE_NAME || '_changes');
BEGIN
IF TG_OP = 'INSERT' THEN
PERFORM pg_notify(channel_name, '{"id": "' || NEW.id || '"}');
RETURN NEW;
END IF;
IF TG_OP = 'DELETE' THEN
PERFORM pg_notify(channel_name, '{"id": "' || OLD.id || '"}');
RETURN OLD;
END IF;
IF TG_OP = 'UPDATE' THEN
PERFORM pg_notify(channel_name, '{"id": "' || NEW.id || '"}');
RETURN NEW;
END IF;
END;
$$ LANGUAGE plpgsql;
DROP TRIGGER IF EXISTS users_changes_trigger on users;
CREATE TRIGGER users_changes_trigger AFTER INSERT OR UPDATE OR DELETE ON users FOR EACH ROW EXECUTE PROCEDURE notify_trigger();
@elgalu
Copy link

elgalu commented Mar 21, 2018

Hi @bithavoc why did you migrate off RethinkDB?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment