Skip to content

Instantly share code, notes, and snippets.

@ssadler
Created July 13, 2014 11:44
Show Gist options
  • Save ssadler/1226a66adceb75998649 to your computer and use it in GitHub Desktop.
Save ssadler/1226a66adceb75998649 to your computer and use it in GitHub Desktop.
simple db pooling actor style
module DB where
import Control.Concurrent.MVar
import Control.Concurrent (forkIO)
import Control.Monad (forever, replicateM)
import Database.PostgreSQL.Simple
type QueryFunc a = Connection -> IO a
type DBActor = MVar (QueryFunc ())
forkDBActors params n = do
inbox <- newEmptyMVar
replicateM n $ do
forkIO $ do
conn <- connectPostgreSQL params
forever $ do
query <- takeMVar inbox
query conn
return ()
return inbox
withDB :: DBActor -> QueryFunc a -> IO a
withDB qbox query = do
abox <- newEmptyMVar
putMVar qbox $ \conn -> query conn >>= putMVar abox
takeMVar abox
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment