1- module Gargoyle.PostgreSQL.Connect (withDb , openDb ) where
1+ {-# LANGUAGE LambdaCase #-}
2+ module Gargoyle.PostgreSQL.Connect
3+ ( openDb
4+ , withDb
5+ , withDbConnString
6+ ) where
27
3- import Control.Monad ((>=> ) )
8+ import Control.Monad ((<=< ) )
49import Data.ByteString (ByteString )
510import qualified Data.ByteString.Char8 as C8
611import Data.Pool (Pool , createPool )
@@ -18,15 +23,26 @@ import System.Directory (doesFileExist)
1823-- order to open and start the database. Otherwise, it will create the
1924-- database for you if it doesn't exist.
2025withDb :: String -> (Pool Connection -> IO a ) -> IO a
21- withDb dbPath a = do
26+ withDb dbPath k = do
2227 dbExists <- doesFileExist dbPath
23- if dbExists
28+ flip withDbConnString k =<< if dbExists
2429 -- use the file contents as the uri for an existing server
25- then C8. readFile dbPath >>= openDb . head . C8. lines >>= a
30+ then Left . head . C8. lines <$> C8. readFile dbPath
2631 -- otherwise assume it's a folder for a local database
27- else do
28- g <- postgresNix
29- withGargoyle g dbPath $ openDb >=> a
32+ else pure $ Right dbPath
33+
34+ -- | Either connects to a database at the given connection string in the Left
35+ -- case, or uses gargoyle at the filepath specified in the Right case. Allows
36+ -- to keep the connection string at a different place from the gargoyle
37+ -- cluster.
38+ withDbConnString :: Either ByteString FilePath -> (Pool Postgresql -> IO a ) -> IO a
39+ withDbConnString = \ case
40+ -- use the file contents as the uri for an existing server
41+ Left connStr -> (>>=) (openDb connStr)
42+ -- otherwise assume it's a folder for a local database
43+ Right gargoylePath -> \ k -> do
44+ g <- postgresNix
45+ withGargoyle g gargoylePath $ k <=< openDb
3046
3147openDb :: ByteString -> IO (Pool Connection )
3248openDb dbUri = createPool (connectPostgreSQL dbUri) close 1 5 20
0 commit comments