Skip to content

Commit f9126b8

Browse files
committed
Add withDbConnString
In prod, we don't want to use gargoyle and do want to use a setting from a committed config as opposed to an uncommitted file on the db path.
1 parent 1ddbfd1 commit f9126b8

File tree

1 file changed

+24
-8
lines changed
  • gargoyle-postgresql-connect/src/Gargoyle/PostgreSQL

1 file changed

+24
-8
lines changed

gargoyle-postgresql-connect/src/Gargoyle/PostgreSQL/Connect.hs

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
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 ((<=<))
49
import Data.ByteString (ByteString)
510
import qualified Data.ByteString.Char8 as C8
611
import 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.
2025
withDb :: 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

3147
openDb :: ByteString -> IO (Pool Connection)
3248
openDb dbUri = createPool (connectPostgreSQL dbUri) close 1 5 20

0 commit comments

Comments
 (0)