Skip to content

Instantly share code, notes, and snippets.

@zouppen
Last active August 29, 2015 14:15
Show Gist options
  • Select an option

  • Save zouppen/3a40d22934298a5abe7b to your computer and use it in GitHub Desktop.

Select an option

Save zouppen/3a40d22934298a5abe7b to your computer and use it in GitHub Desktop.
Listening to notifications in PostgreSQL
{-# LANGUAGE OverloadedStrings, RecordWildCards #-}
module Main where
import Control.Monad (forever)
import Data.ByteString.Char8 (pack)
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.Notification
import System.Environment (getArgs)
main = do
[connString] <- getArgs
conn <- connectPostgreSQL $ pack connString
execute_ conn "LISTEN change"
forever $ do
Notification{..} <- getNotification conn
print notificationPid
print notificationChannel
print notificationData
<?php
$conn = pg_connect("dbname=my_database");
pg_query($conn, 'LISTEN change;');
while (true) {
// Unfortunately PHP < 5.6 doesn't support synchronous waiting so we
// must poll it once per second.
$notify = pg_get_notify($conn);
if ($notify) break;
sleep(1);
}
print_r($notify);
?>
CREATE OR REPLACE FUNCTION change_notify() RETURNS trigger AS $$ BEGIN EXECUTE 'NOTIFY change,''' || TG_TABLE_NAME || '-' || TG_OP || ''''; RETURN new; END; $$ LANGUAGE plpgsql;
CREATE TRIGGER change_trigger AFTER insert or update or delete or truncate on testi execute procedure change_notify();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment