-- |
-- This module provides a low-level effectful API dealing with the connections to the database.
module Hasql.Connection
  ( Connection,
    acquire,
    release,
    use,
  )
where

import Data.Text.Read qualified as Text.Read
import Hasql.Connection.Config qualified as Config
import Hasql.Connection.ServerVersion qualified as ServerVersion
import Hasql.Connection.Settings qualified as Settings
import Hasql.ConnectionState qualified as ConnectionState
import Hasql.ConnectionState.StatementCache qualified as StatementCache
import Hasql.Engine.Contexts.Session qualified as Session
import Hasql.Engine.Errors
import Hasql.Platform.Prelude
import Pqi (Adapter)
import Pqi qualified as Pq

-- |
-- A single connection to the database.
newtype Connection
  = Connection
      -- |
      -- The state is 'Nothing' once the connection is gone. That happens when
      -- 'release' is called on it, when a session fails in a way that leaves
      -- the driver unable to vouch for the connection's protocol state (a
      -- 'ConnectionUseError' out of 'use'), and when an exception cuts a
      -- session short - in the latter two cases 'use' finishes it. @libpq@
      -- forbids touching a connection after @PQfinish@, so the handle has to
      -- remember that it did: without it a second 'release' finishes a freed
      -- connection and a later 'use' sends on one.
      (MVar (Maybe ConnectionState.ConnectionState))

-- |
-- Establish a connection according to the provided settings.
--
-- The first argument is an 'Pqi.Adapter', which defines the backend
-- implementation used to talk to PostgreSQL (for example, libpq via the
-- <https://hackage.haskell.org/package/pqi-ffi pqi-ffi> package, or a pure
-- Haskell implementation via the
-- <https://hackage.haskell.org/package/pqi-native pqi-native> package).
-- This is the only place in the library where users choose the adapter.
--
-- This function:
--
-- - Opens a PostgreSQL connection using the constructed connection string.
-- - Validates that the connection is healthy.
-- - Checks the server version for compatibility.
-- - Initializes session-level settings (encoding and message verbosity).
--
-- On success, returns a 'Connection' wrapped in 'Right'.
-- On failure, returns a classified 'AcquireError' in 'Left'.
acquire ::
  Adapter ->
  Settings.Settings ->
  IO (Either AcquireError Connection)
acquire :: Adapter -> Settings -> IO (Either AcquireError Connection)
acquire Adapter
adapter Settings
settings =
  {-# SCC "acquire" #-}
  ExceptT AcquireError IO Connection
-> IO (Either AcquireError Connection)
forall e (m :: * -> *) a. ExceptT e m a -> m (Either e a)
runExceptT do
    let config :: Config
config = Settings -> Config
forall a. Constructs a => a -> Config
Config.construct Settings
settings

    -- Connect:
    IO (Either AcquireError Connection)
-> ExceptT AcquireError IO Connection
forall e (m :: * -> *) a. m (Either e a) -> ExceptT e m a
ExceptT do
      IO Connection
-> (Connection -> IO ())
-> (Connection -> IO (Either AcquireError Connection))
-> IO (Either AcquireError Connection)
forall a b c. IO a -> (a -> IO b) -> (a -> IO c) -> IO c
bracketOnError
        (Adapter -> ByteString -> IO Connection
Pq.connectdb Adapter
adapter (Config -> ByteString
Config.connectionString Config
config))
        Connection -> IO ()
Pq.finish
        \Connection
pqConnection -> do
          Either AcquireError Connection
result <- ExceptT AcquireError IO Connection
-> IO (Either AcquireError Connection)
forall e (m :: * -> *) a. ExceptT e m a -> m (Either e a)
runExceptT do
            -- Check status:
            ConnStatus
status <- IO ConnStatus -> ExceptT AcquireError IO ConnStatus
forall (m :: * -> *) a. Monad m => m a -> ExceptT AcquireError m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (Connection -> IO ConnStatus
Pq.status Connection
pqConnection)
            case ConnStatus
status of
              ConnStatus
Pq.ConnectionOk -> () -> ExceptT AcquireError IO ()
forall a. a -> ExceptT AcquireError IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
              ConnStatus
_ -> do
                Bool
needsPassword <- IO Bool -> ExceptT AcquireError IO Bool
forall (m :: * -> *) a. Monad m => m a -> ExceptT AcquireError m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (Connection -> IO Bool
Pq.connectionNeedsPassword Connection
pqConnection)
                Maybe ByteString
errorMessage <- IO (Maybe ByteString) -> ExceptT AcquireError IO (Maybe ByteString)
forall (m :: * -> *) a. Monad m => m a -> ExceptT AcquireError m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (Connection -> IO (Maybe ByteString)
Pq.errorMessage Connection
pqConnection)
                let errorText :: Text
errorText = Text -> (ByteString -> Text) -> Maybe ByteString -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"" ByteString -> Text
decodeUtf8Lenient Maybe ByteString
errorMessage
                AcquireError -> ExceptT AcquireError IO ()
forall a. AcquireError -> ExceptT AcquireError IO a
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError
                  if Bool
needsPassword
                    then Text -> AcquireError
ConnectionPasswordRequiredAcquireError Text
errorText
                    else Text -> AcquireError
ConnectionAcquireError Text
errorText

            -- Check version:
            ServerVersion
version <- IO ServerVersion -> ExceptT AcquireError IO ServerVersion
forall (m :: * -> *) a. Monad m => m a -> ExceptT AcquireError m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (Connection -> IO ServerVersion
ServerVersion.load Connection
pqConnection)
            Bool -> ExceptT AcquireError IO () -> ExceptT AcquireError IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (ServerVersion
version ServerVersion -> ServerVersion -> Bool
forall a. Ord a => a -> a -> Bool
< ServerVersion
ServerVersion.minimum) do
              case ServerVersion
version of
                ServerVersion.ServerVersion Int
major Int
minor Int
patch ->
                  AcquireError -> ExceptT AcquireError IO ()
forall a. AcquireError -> ExceptT AcquireError IO a
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError (Int -> Int -> Int -> AcquireError
VersionTooOldAcquireError Int
major Int
minor Int
patch)

            -- Initialize:
            do
              Maybe Result
execResult <-
                IO (Maybe Result) -> ExceptT AcquireError IO (Maybe Result)
forall (m :: * -> *) a. Monad m => m a -> ExceptT AcquireError m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift do
                  Connection -> ByteString -> IO (Maybe Result)
Pq.exec Connection
pqConnection do
                    ByteString
"SET client_encoding = 'UTF8';\n\
                    \SET client_min_messages TO WARNING;"
              case Maybe Result
execResult of
                Maybe Result
Nothing -> do
                  Maybe ByteString
errorMessage <- IO (Maybe ByteString) -> ExceptT AcquireError IO (Maybe ByteString)
forall (m :: * -> *) a. Monad m => m a -> ExceptT AcquireError m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (Connection -> IO (Maybe ByteString)
Pq.errorMessage Connection
pqConnection)
                  AcquireError -> ExceptT AcquireError IO ()
forall a. AcquireError -> ExceptT AcquireError IO a
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError (Text -> AcquireError
InitializationConnectionLossAcquireError (Text -> (ByteString -> Text) -> Maybe ByteString -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"" ByteString -> Text
decodeUtf8Lenient Maybe ByteString
errorMessage))
                Just Result
result -> do
                  ExecStatus
status <- IO ExecStatus -> ExceptT AcquireError IO ExecStatus
forall (m :: * -> *) a. Monad m => m a -> ExceptT AcquireError m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (Result -> IO ExecStatus
Pq.resultStatus Result
result)
                  case ExecStatus
status of
                    ExecStatus
Pq.CommandOk -> () -> ExceptT AcquireError IO ()
forall a. a -> ExceptT AcquireError IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
                    ExecStatus
_ -> do
                      Maybe ByteString
sqlstate <- IO (Maybe ByteString) -> ExceptT AcquireError IO (Maybe ByteString)
forall (m :: * -> *) a. Monad m => m a -> ExceptT AcquireError m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (Result -> FieldCode -> IO (Maybe ByteString)
Pq.resultErrorField Result
result FieldCode
Pq.DiagSqlstate)
                      case Maybe ByteString
sqlstate of
                        Just ByteString
code | ByteString
code ByteString -> ByteString -> Bool
forall a. Eq a => a -> a -> Bool
/= ByteString
"" -> do
                          ServerError
serverError <- IO ServerError -> ExceptT AcquireError IO ServerError
forall (m :: * -> *) a. Monad m => m a -> ExceptT AcquireError m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (Result -> Text -> IO ServerError
loadServerError Result
result (ByteString -> Text
decodeUtf8Lenient ByteString
code))
                          AcquireError -> ExceptT AcquireError IO ()
forall a. AcquireError -> ExceptT AcquireError IO a
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError (ServerError -> AcquireError
InitializationServerErrorAcquireError ServerError
serverError)
                        Maybe ByteString
_ -> do
                          Maybe ByteString
errorMessage <- IO (Maybe ByteString) -> ExceptT AcquireError IO (Maybe ByteString)
forall (m :: * -> *) a. Monad m => m a -> ExceptT AcquireError m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (Result -> IO (Maybe ByteString)
Pq.resultErrorMessage Result
result)
                          AcquireError -> ExceptT AcquireError IO ()
forall a. AcquireError -> ExceptT AcquireError IO a
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError (Text -> AcquireError
InitializationConnectionLossAcquireError (Text -> (ByteString -> Text) -> Maybe ByteString -> Text
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Text
"" ByteString -> Text
decodeUtf8Lenient Maybe ByteString
errorMessage))

            let connectionState :: ConnectionState
connectionState =
                  ConnectionState.ConnectionState
                    { preparedStatements :: Bool
ConnectionState.preparedStatements = Bool -> Bool
not (Config -> Bool
Config.noPreparedStatements Config
config),
                      statementCache :: StatementCache
ConnectionState.statementCache = StatementCache
StatementCache.empty,
                      oidCache :: OidCache
ConnectionState.oidCache = OidCache
forall a. Monoid a => a
mempty,
                      connection :: Connection
ConnectionState.connection = Connection
pqConnection
                    }
            MVar (Maybe ConnectionState)
connectionRef <- IO (MVar (Maybe ConnectionState))
-> ExceptT AcquireError IO (MVar (Maybe ConnectionState))
forall (m :: * -> *) a. Monad m => m a -> ExceptT AcquireError m a
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (Maybe ConnectionState -> IO (MVar (Maybe ConnectionState))
forall a. a -> IO (MVar a)
newMVar (ConnectionState -> Maybe ConnectionState
forall a. a -> Maybe a
Just ConnectionState
connectionState))
            pure (MVar (Maybe ConnectionState) -> Connection
Connection MVar (Maybe ConnectionState)
connectionRef)

          -- A classified failure (as opposed to a thrown exception, which
          -- 'bracketOnError' already finishes the connection for) still
          -- needs the connection finished, since it doesn't escape this
          -- action as an exception.
          case Either AcquireError Connection
result of
            Left AcquireError
_ -> Connection -> IO ()
Pq.finish Connection
pqConnection
            Right Connection
_ -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
          pure Either AcquireError Connection
result
  where
    -- Read the structured error report off a result, once its SQLSTATE field
    -- is known to be present.
    loadServerError :: Pq.Result -> Text -> IO ServerError
    loadServerError :: Result -> Text -> IO ServerError
loadServerError Result
result Text
code = do
      ByteString
message <- Maybe ByteString -> ByteString
forall m. Monoid m => Maybe m -> m
forall (t :: * -> *) m. (Foldable t, Monoid m) => t m -> m
fold (Maybe ByteString -> ByteString)
-> IO (Maybe ByteString) -> IO ByteString
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Result -> FieldCode -> IO (Maybe ByteString)
Pq.resultErrorField Result
result FieldCode
Pq.DiagMessagePrimary
      Maybe ByteString
detail <- Result -> FieldCode -> IO (Maybe ByteString)
Pq.resultErrorField Result
result FieldCode
Pq.DiagMessageDetail
      Maybe ByteString
hint <- Result -> FieldCode -> IO (Maybe ByteString)
Pq.resultErrorField Result
result FieldCode
Pq.DiagMessageHint
      Maybe ByteString
position <- Result -> FieldCode -> IO (Maybe ByteString)
Pq.resultErrorField Result
result FieldCode
Pq.DiagStatementPosition
      pure
        $ Text
-> Text -> Maybe Text -> Maybe Text -> Maybe Int -> ServerError
ServerError
          Text
code
          (ByteString -> Text
decodeUtf8Lenient ByteString
message)
          ((ByteString -> Text) -> Maybe ByteString -> Maybe Text
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ByteString -> Text
decodeUtf8Lenient Maybe ByteString
detail)
          ((ByteString -> Text) -> Maybe ByteString -> Maybe Text
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ByteString -> Text
decodeUtf8Lenient Maybe ByteString
hint)
          (Maybe ByteString -> Maybe Int
parsePosition Maybe ByteString
position)

    parsePosition :: Maybe ByteString -> Maybe Int
    parsePosition :: Maybe ByteString -> Maybe Int
parsePosition = \case
      Maybe ByteString
Nothing -> Maybe Int
forall a. Maybe a
Nothing
      Just ByteString
bytes -> case Reader Int
forall a. Integral a => Reader a
Text.Read.decimal (ByteString -> Text
decodeUtf8Lenient ByteString
bytes) of
        Right (Int
n, Text
"") -> Int -> Maybe Int
forall a. a -> Maybe a
Just Int
n
        Either String (Int, Text)
_ -> Maybe Int
forall a. Maybe a
Nothing

-- |
-- Release the connection.
--
-- Idempotent: releasing a connection that is already gone - released
-- before, or finished by 'use' - does nothing.
release :: Connection -> IO ()
release :: Connection -> IO ()
release (Connection MVar (Maybe ConnectionState)
var) =
  IO () -> IO ()
forall a. IO a -> IO a
mask_ do
    Maybe ConnectionState
connectionState <- MVar (Maybe ConnectionState) -> IO (Maybe ConnectionState)
forall a. MVar a -> IO a
takeMVar MVar (Maybe ConnectionState)
var
    -- The handle is marked spent before the connection is touched, so that a
    -- 'Pq.finish' that somehow fails leaves the handle unusable rather than
    -- the MVar empty forever.
    MVar (Maybe ConnectionState) -> Maybe ConnectionState -> IO ()
forall a. MVar a -> a -> IO ()
putMVar MVar (Maybe ConnectionState)
var Maybe ConnectionState
forall a. Maybe a
Nothing
    (ConnectionState -> IO ()) -> Maybe ConnectionState -> IO ()
forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
(a -> f b) -> t a -> f ()
traverse_ (Connection -> IO ()
Pq.finish (Connection -> IO ())
-> (ConnectionState -> Connection) -> ConnectionState -> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
forall {k} (cat :: k -> k -> *) (b :: k) (c :: k) (a :: k).
Category cat =>
cat b c -> cat a b -> cat a c
. ConnectionState -> Connection
ConnectionState.connection) Maybe ConnectionState
connectionState

-- |
-- Execute a sequence of operations with exclusive access to the connection.
--
-- Blocks until the connection is available when there is another session running upon the connection on a different thread.
--
-- An exception thrown out of the session - including an interruption
-- delivered from another thread, as 'System.Timeout.timeout' and
-- 'Control.Concurrent.killThread' do - propagates, and the connection is
-- finished on the way out. See the note on the exception path below for why
-- it is not repaired instead.
use :: Connection -> Session.Session a -> IO (Either UseError a)
use :: forall a. Connection -> Session a -> IO (Either UseError a)
use (Connection MVar (Maybe ConnectionState)
var) Session a
session =
  ((forall a. IO a -> IO a) -> IO (Either UseError a))
-> IO (Either UseError a)
forall b. ((forall a. IO a -> IO a) -> IO b) -> IO b
mask \forall a. IO a -> IO a
unmask -> do
    MVar (Maybe ConnectionState) -> IO (Maybe ConnectionState)
forall a. MVar a -> IO a
takeMVar MVar (Maybe ConnectionState)
var IO (Maybe ConnectionState)
-> (Maybe ConnectionState -> IO (Either UseError a))
-> IO (Either UseError a)
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
      Maybe ConnectionState
Nothing -> do
        MVar (Maybe ConnectionState) -> Maybe ConnectionState -> IO ()
forall a. MVar a -> a -> IO ()
putMVar MVar (Maybe ConnectionState)
var Maybe ConnectionState
forall a. Maybe a
Nothing
        pure (UseError -> Either UseError a
forall a b. a -> Either a b
Left (Text -> UseError
ConnectionUseError Text
"The connection is no longer available"))
      Just ConnectionState
connectionState -> do
        (Either UseError a
result, !ConnectionState
newState) <-
          IO (Either UseError a, ConnectionState)
-> IO () -> IO (Either UseError a, ConnectionState)
forall a b. IO a -> IO b -> IO a
onException (IO (Either UseError a, ConnectionState)
-> IO (Either UseError a, ConnectionState)
forall a. IO a -> IO a
unmask (Session a
-> ConnectionState -> IO (Either UseError a, ConnectionState)
forall a.
Session a
-> ConnectionState -> IO (Either UseError a, ConnectionState)
Session.run Session a
session ConnectionState
connectionState)) do
            -- An exception leaves the connection somewhere inside a round
            -- trip, and the driver has no way of finding out where. Repairing
            -- it means draining results and aborting the transaction -
            -- blocking network IO, performed here under a mask, which on a
            -- connection whose peer has gone away never returns. The
            -- interruption being handled would then never land, which is the
            -- opposite of what the caller asked for. Finishing the connection
            -- touches nothing but the socket.
            --
            -- The connection finished here is the one taken out of the MVar. A
            -- session that replaced it through 'Hasql.Session.onLibpqConnection'
            -- loses the replacement along with the rest of the state the
            -- exception unwound past; closing that one is on the caller, which
            -- is what the escape hatch already promises.
            MVar (Maybe ConnectionState) -> Maybe ConnectionState -> IO ()
forall a. MVar a -> a -> IO ()
putMVar MVar (Maybe ConnectionState)
var Maybe ConnectionState
forall a. Maybe a
Nothing
            Connection -> IO ()
Pq.finish (ConnectionState -> Connection
ConnectionState.connection ConnectionState
connectionState)

        -- The driver gave up on the connection somewhere inside the session,
        -- and by construction that verdict is what 'result' says: nothing
        -- further inside the session could have caught it and carried on.
        let finish :: IO ()
finish = do
              MVar (Maybe ConnectionState) -> Maybe ConnectionState -> IO ()
forall a. MVar a -> a -> IO ()
putMVar MVar (Maybe ConnectionState)
var Maybe ConnectionState
forall a. Maybe a
Nothing
              Connection -> IO ()
Pq.finish (ConnectionState -> Connection
ConnectionState.connection ConnectionState
newState)
        case Either UseError a
result of
          Left (ConnectionUseError Text
_) -> IO ()
finish
          Either UseError a
_ -> MVar (Maybe ConnectionState) -> Maybe ConnectionState -> IO ()
forall a. MVar a -> a -> IO ()
putMVar MVar (Maybe ConnectionState)
var (ConnectionState -> Maybe ConnectionState
forall a. a -> Maybe a
Just ConnectionState
newState)

        pure Either UseError a
result