Module notify

June 1, 2026 · View on GitHub

⤌ Back

Module notify

High-level LISTEN / NOTIFY support for real-time PostgreSQL notifications. PostgreSQL's NOTIFY mechanism allows one database session to signal other listening sessions asynchronously, enabling lightweight pub/sub patterns without polling.

Example

import postgres { Connection }
var conn = Connection('postgres://localhost/mydb')
conn.connect()
var listener = conn.listen('chat_messages')
# Register a callback for incoming notifications.
listener.on(@(notification) {
  echo 'Channel: ' + notification.channel
  echo 'Payload: ' + notification.payload
  echo 'PID:     ' + notification.pid
})
# Poll for notifications (non-blocking check).
listener.poll()
# Stop listening and free resources.
listener.close()
conn.close()

Classes

class NotificationListener

Subscribes to one or more PostgreSQL NOTIFY channels on a connection and delivers incoming notifications to registered callback functions. NotificationListener is obtained via Connection.listen(), not by constructing directly.

This module implements the following decorated functions: @to_string.

Properties

  • channels (list)

    The channels this listener is subscribed to.

Methods

  • NotificationListener(protocol, channels) (Constructor)

  • subscribe(channel)

    Subscribes to an additional channel.

    Parameters

    • string channel The PostgreSQL channel name to listen on.
  • unsubscribe(channel)

    Unsubscribes from a specific channel.

    Parameters

    • string channel The channel to stop listening on.
  • on(fn)

    Registers a callback function to be invoked when a notification arrives. The callback receives a single dict argument with keys:

    • channel — the channel name (string)
    • payload — the notification payload (string, may be empty)
    • pid — the notifying backend's process ID (number) Multiple callbacks may be registered; they are called in order.
    listener.on(@(n) {
      echo n.channel + ': ' + n.payload
    })
    

    Parameters

    • function fn The callback to register.
  • poll()

    Performs a single non-blocking poll of the connection for pending notifications. Any notifications found are dispatched to all registered callbacks. Call this in an event loop or from a timer to process notifications.

  • wait(interval_ms, max_count)

    Blocks, polling for notifications every interval_ms milliseconds until stop() is called or max_count notifications have been received (0 = no limit).Note:* This is a simple busy-wait loop. For production use consider running the listener in a dedicated thread using Zuri's thread module.

    Parameters

    • number interval_ms Poll interval in milliseconds (default 200).

    • number max_count Stop after receiving this many notifications (0 = run forever, default).

  • stop()

    Signals an in-progress wait() call to stop.

  • close()

    Unsubscribes from all channels and releases the listener. The underlying connection remains open.