Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a pg_notify notification for every inserted row in postgres?

I'm trying to fire a pg_notify whenever a new row gets inserted into a table, but instead of getting a notification for every newly-inserted row, I only get one notification in total.

The trigger is

CREATE TRIGGER "testNotify"
AFTER INSERT ON mine.test
FOR EACH ROW EXECUTE PROCEDURE mine."testNotify"()

The function is

CREATE OR REPLACE FUNCTION mine."testNotify"()
  RETURNS TRIGGER AS $$
DECLARE
BEGIN
  PERFORM pg_notify('testNotify', 'test payload');
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

The insert is

INSERT INTO mine.test (one, two, three)
SELECT one, two, three FROM temptable
ON CONFLICT DO NOTHING

I've successfully inserted about new 100,000 rows this way, so I would expect to see that many notifications if my application does LISTEN "testNotify", but instead it gets only 1, with a channel of testNotify and a payload of test payload. Am I doing something wrong above?

like image 244
user779159 Avatar asked Feb 20 '17 14:02

user779159


1 Answers

Quote from the manual

If the same channel name is signaled multiple times from the same transaction with identical payload strings, the database server can decide to deliver a single notification only.

(emphasis mine)

And:

On the other hand, notifications with distinct payload strings will always be delivered as distinct notifications

So, if you want to make sure you get one notification for each row, include the primary key of the row in the payload.

like image 83
a_horse_with_no_name Avatar answered Oct 15 '22 10:10

a_horse_with_no_name