Last active
August 29, 2015 14:15
-
-
Save zouppen/3a40d22934298a5abe7b to your computer and use it in GitHub Desktop.
Listening to notifications in PostgreSQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| {-# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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); | |
| ?> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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