@@ -19,6 +19,7 @@
19module Database.PostgreSQL.Simple.Notification
19module Database.PostgreSQL.Simple.Notification
20 ( Notification(..)
20 ( Notification(..)
21 , getNotification
21 , getNotification
22+ , getNotificationIfAvailable
24import Control.Concurrent ( threadWaitRead )
25import Control.Concurrent ( threadWaitRead )
@@ -38,6 +39,11 @@ errfd :: String
38errfd = "Database.PostgreSQL.Simple.Notification.getNotification: \
39errfd = "Database.PostgreSQL.Simple.Notification.getNotification: \
39 \failed to fetch file descriptor"
40 \failed to fetch file descriptor"
42+convertNotice :: PQ.Notify -> Notification
43+convertNotice PQ.Notify{..}
44+ = Notification { notificationPid = notifyBePid
45+ , notificationChannel = notifyRelname
46+ , notificationData = notifyExtra }
42-- | Returns a single notification. If no notifications are available,
48-- | Returns a single notification. If no notifications are available,
43-- 'getNotification' blocks until one arrives.
49-- 'getNotification' blocks until one arrives.
@@ -55,10 +61,24 @@ getNotification = loop False
55 case mfd of
61 case mfd of
56 Nothing -> fail errfd
62 Nothing -> fail errfd
57 Just fd -> return (Left fd)
63 Just fd -> return (Left fd)
58− Just x -> return (Right x)
64+ Just msg -> return (Right msg)
65+ -- FIXME? what happens if the connection is closed/reset right here?
59 case res of
66 case res of
60 Left fd -> threadWaitRead fd >> loop True conn
67 Left fd -> threadWaitRead fd >> loop True conn
61− Right PQ.Notify{..} -> do
68+ Right msg -> return $! convertNotice msg
62− return Notification { notificationPid = notifyBePid
69+
63− , notificationChannel = notifyRelname
70+-- | Non-blocking variant of 'getNotification'. Returns a single notification,
64− , notificationData = notifyExtra }
71+-- if available. If no notifications are available, returns 'Nothing'.
73+getNotificationIfAvailable :: Connection -> IO (Maybe Notification)
74+getNotificationIfAvailable conn =
75+ withConnection conn $ \c -> do
76+ mmsg <- PQ.notifies c
78+ Just msg -> return $! Just $! convertNotice msg
80+ _ <- PQ.consumeInput c
81+ mmsg' <- PQ.notifies c
83+ Just msg -> return $! Just $! convertNotice msg
84+ Nothing -> return Nothing