module Hasql.Pool.Extended where

import Data.Map as Map
import Hasql.Connection.Setting qualified as HasqlSetting
import Hasql.Connection.Setting.Connection qualified as HasqlConn
import Hasql.Connection.Setting.Connection.Param qualified as HasqlConfig
import Hasql.Pool as HasqlPool
import Hasql.Pool.Config qualified as HasqlPool
import Imports
import Util.Options

-- | Creates a pool from postgres config params
--
-- HasqlConn.params translates pgParams into connection (which just holds the connection string and is not a real connection)
-- HasqlSetting.connection unwraps the connection string out of connection
-- HasqlPool.staticConnectionSettings translates the connection string to the pool settings
-- HasqlPool.settings translates the pool settings into pool config
-- HasqlPool.acquire creates the pool.
-- ezpz.
initPostgresPool :: Map Text Text -> Maybe FilePathSecrets -> IO HasqlPool.Pool
initPostgresPool :: Map Text Text -> Maybe FilePathSecrets -> IO Pool
initPostgresPool Map Text Text
pgConfig Maybe FilePathSecrets
mFpSecrets = do
  Maybe Text
mPw <- Maybe FilePathSecrets
-> (FilePathSecrets -> IO Text) -> IO (Maybe Text)
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
t a -> (a -> f b) -> f (t b)
for Maybe FilePathSecrets
mFpSecrets FilePathSecrets -> IO Text
forall (m :: * -> *) a.
(MonadIO m, FromJSON a) =>
FilePathSecrets -> m a
initCredentials
  let pgConfigWithPw :: Map Text Text
pgConfigWithPw = Map Text Text
-> (Text -> Map Text Text) -> Maybe Text -> Map Text Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Map Text Text
pgConfig (\Text
pw -> Text -> Text -> Map Text Text -> Map Text Text
forall k a. Ord k => k -> a -> Map k a -> Map k a
Map.insert Text
"password" Text
pw Map Text Text
pgConfig) Maybe Text
mPw
      pgParams :: [Param]
pgParams = (Text -> Text -> [Param]) -> Map Text Text -> [Param]
forall m k a. Monoid m => (k -> a -> m) -> Map k a -> m
Map.foldMapWithKey (\Text
k Text
v -> [Text -> Text -> Param
HasqlConfig.other Text
k Text
v]) Map Text Text
pgConfigWithPw
  Config -> IO Pool
HasqlPool.acquire (Config -> IO Pool) -> Config -> IO Pool
forall a b. (a -> b) -> a -> b
$
    [Setting] -> Config
HasqlPool.settings
      [ [Setting] -> Setting
HasqlPool.staticConnectionSettings ([Setting] -> Setting) -> [Setting] -> Setting
forall a b. (a -> b) -> a -> b
$
          [Connection -> Setting
HasqlSetting.connection (Connection -> Setting) -> Connection -> Setting
forall a b. (a -> b) -> a -> b
$ [Param] -> Connection
HasqlConn.params [Param]
pgParams]
      ]