PostgreSQL supports asynchronous notification via the LISTEN and NOTIFY commands. A backend registers its interest in a particular notification condition with the LISTEN command (and can stop listening with the UNLISTEN command). All backends listening on a particular condition will be notified asynchronously when a NOTIFY of that condition name is executed by any backend. No additional information is passed from the notifier to the listener. Thus, typically, any actual data that needs to be communicated is transferred through a database relation. Commonly the condition name is the same as the associated relation, but it is not necessary for there to be any associated relation.
libpq applications submit LISTEN and UNLISTEN commands as ordinary SQL command. Subsequently, arrival of NOTIFY messages can be detected by calling PQ-notifies.
PQ-notifies returns the next notification from a list of unhandled notification messages received from the backend. Returns #f if there are no pending notifications. Once a notification is returned from PQ-notifies, it is considered handled and will be removed from the list of notifications.
(PQ-notifies conn)
Returns a PGnotify foreign object pointer or #f. Notification is represented as a foreign structure PGnotify, that has two fields
(PG-notify-relname notification)
After processing a PGnotify object pointer returned by PQ-notifies, be sure to free it with (PQ-free-notify notify) to avoid a memory leak.
Note: In PostgreSQL 6.4 and later, the be_pid is that of the notifying backend, whereas in earlier versions it was always the PID of your own backend.
PQ-notifies does not actually read backend data; it just returns messages previously absorbed by another libpq function. In prior releases of libpq, the only way to ensure timely receipt of NOTIFY messages was to constantly submit queries, even empty ones, and then check PQ-notifies after each PQ-exec call. While this still works, it is deprecated as a waste of processing power.