Skip to content

Instantly share code, notes, and snippets.

@sergeysova
Forked from fritzy/1_triggers.sql
Last active March 23, 2020 10:56
Show Gist options
  • Save sergeysova/4b2639c513485938d7ea64afa639442b to your computer and use it in GitHub Desktop.
Save sergeysova/4b2639c513485938d7ea64afa639442b to your computer and use it in GitHub Desktop.
Get table change notifications from Postgres as JSON
CREATE OR REPLACE FUNCTION table_update_notify() RETURNS trigger AS $$
DECLARE
id UUID;
BEGIN
IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN
id = NEW.id;
ELSE
id = OLD.id;
END IF;
PERFORM pg_notify('table_update', json_build_object('table', TG_TABLE_NAME, 'type', TG_OP, 'record', NEW, 'prev', OLD)::text);
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
DROP TRIGGER users_notify_update ON users;
CREATE TRIGGER users_notify_update AFTER UPDATE ON users FOR EACH ROW EXECUTE PROCEDURE table_update_notify();
DROP TRIGGER users_notify_insert ON users;
CREATE TRIGGER users_notify_insert AFTER INSERT ON users FOR EACH ROW EXECUTE PROCEDURE table_update_notify();
DROP TRIGGER users_notify_delete ON users;
CREATE TRIGGER users_notify_delete AFTER DELETE ON users FOR EACH ROW EXECUTE PROCEDURE table_update_notify();
const { Client } = require("pg");
async function main() {
const pg = new Client("postgres://localhost/authmenow");
await pg.connect();
console.log("Connected");
pg.on("notification", function(msg) {
console.log("NOTIFICATION", msg);
if (msg.name === "notification" && msg.channel === "table_update") {
var pl = JSON.parse(msg.payload);
console.log("*========*");
Object.keys(pl).forEach(function(key) {
console.log(key, pl[key]);
});
console.log("-========-");
}
});
pg.query("LISTEN table_update");
}
main().catch(e => {
console.error(e);
process.exit(-1);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment