Description
The NOTIFY command is the counterpart of the LISTEN command, which we covered earlier in this chapter. The two commands provide a simple interprocess communication (IPC) implementation that can often prove useful if used correctly.
Use NOTIFY to send out a notification with the specified name; if any frontends have issued a LISTEN command with the same notification name, they will be informed of the notification.
Note: The behavior of a frontend process after receiving a notification sent by the NOTIFY command is dependent upon its implementation of the feature, so it may not respond immediately (or at all).
A notification is comprised of the notification's name and the issuing backend's process ID (PID). The original designer of the database specifies what notify condition names exist and how they function within the database.
The NOTIFY and LISTEN commands are most often used to provide a way to notify frontend processes that tables have been modified; as such, notification names are often set to the names of tables. This is the
common
use of this feature, but it is not required that notification names be table names.
Note: Automatic notification of table modifications can be achieved by placing the NOTIFY command in a rule that gets triggered by table updates.
Transactions
It is important to note how NOTIFY behaves when used with transactions. Most importantly, any NOTIFY commands executed within a transaction will not be delivered until after the transaction is committed. This behavior prevents notifications from being sent out from aborted transactions.
Also important is that a backend will not deliver a notification to its connected frontend if a transaction is in progress. If a frontend process is currently within a transaction, the backend will wait to send a notification until that transaction has been terminated with either a COMMIT or ROLLBACK.
Multiple signals
The NOTIFY/LISTEN system works in a way that is very similar to that of UNIX signals. Even if the same notification is signaled multiple times using multiple NOTIFY commands, that notification may only be sent to listening processes only
once
, instead of however many times it was signaled.
Because of this design feature, you cannot use the number of received notifications as a counter or to track anything important within your database. The correct way to achieve tracking or counting would be to use NOTIFY with a sequence object (or something similar) to wake applications and track or count actions and events.
Example
The following example defines a notify event to listen for, and then notifies the backend process that the event was reached:
booktown=#
LISTEN publisher_deletion;
LISTEN
booktown=#
NOTIFY publisher_deletion;
Asynchronous NOTIFY 'publisher_deletion' from backend with pid '16864' received.