module Hasql.Private.Connection
where
import Hasql.Private.Prelude
import qualified Database.PostgreSQL.LibPQ as LibPQ
import qualified Hasql.Private.PreparedStatementRegistry as PreparedStatementRegistry
import qualified Hasql.Private.IO as IO
import qualified Hasql.Private.Settings as Settings
data Connection =
Connection !(MVar LibPQ.Connection) !Bool !PreparedStatementRegistry.PreparedStatementRegistry
type ConnectionError =
Maybe ByteString
acquire :: Settings.Settings -> IO (Either ConnectionError Connection)
acquire settings =
{-# SCC "acquire" #-}
runExceptT $ do
pqConnection <- lift (IO.acquireConnection settings)
lift (IO.checkConnectionStatus pqConnection) >>= traverse throwError
lift (IO.initConnection pqConnection)
integerDatetimes <- lift (IO.getIntegerDatetimes pqConnection)
registry <- lift (IO.acquirePreparedStatementRegistry)
pqConnectionRef <- lift (newMVar pqConnection)
pure (Connection pqConnectionRef integerDatetimes registry)
release :: Connection -> IO ()
release (Connection pqConnectionRef _ _) =
mask_ $ do
nullConnection <- LibPQ.newNullConnection
pqConnection <- swapMVar pqConnectionRef nullConnection
IO.releaseConnection pqConnection
withLibPQConnection :: Connection -> (LibPQ.Connection -> IO a) -> IO a
withLibPQConnection (Connection pqConnectionRef _ _) =
withMVar pqConnectionRef