Created
July 13, 2014 11:44
-
-
Save ssadler/1226a66adceb75998649 to your computer and use it in GitHub Desktop.
simple db pooling actor style
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
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