{-|
Extras for the resource-pool library.
-}
module Hasql.Pool.ResourcePool
where

import Hasql.Pool.Prelude
import Data.Pool


withResourceOnEither :: Pool resource -> (resource -> IO (Either failure success)) -> IO (Either failure success)
withResourceOnEither :: Pool resource
-> (resource -> IO (Either failure success))
-> IO (Either failure success)
withResourceOnEither Pool resource
pool resource -> IO (Either failure success)
act = IO (Either failure success) -> IO (Either failure success)
forall a. IO a -> IO a
mask_ (IO (Either failure success) -> IO (Either failure success))
-> IO (Either failure success) -> IO (Either failure success)
forall a b. (a -> b) -> a -> b
$ do
    (resource
resource, LocalPool resource
localPool) <- Pool resource -> IO (resource, LocalPool resource)
forall a. Pool a -> IO (a, LocalPool a)
takeResource Pool resource
pool
    Either failure success
failureOrSuccess      <- resource -> IO (Either failure success)
act resource
resource IO (Either failure success) -> IO () -> IO (Either failure success)
forall a b. IO a -> IO b -> IO a
`onException` Pool resource -> LocalPool resource -> resource -> IO ()
forall a. Pool a -> LocalPool a -> a -> IO ()
destroyResource Pool resource
pool LocalPool resource
localPool resource
resource
    case Either failure success
failureOrSuccess of
        Right success
success -> do
            LocalPool resource -> resource -> IO ()
forall a. LocalPool a -> a -> IO ()
putResource LocalPool resource
localPool resource
resource
            Either failure success -> IO (Either failure success)
forall (m :: * -> *) a. Monad m => a -> m a
return (success -> Either failure success
forall a b. b -> Either a b
Right success
success)
        Left failure
failure -> do
            Pool resource -> LocalPool resource -> resource -> IO ()
forall a. Pool a -> LocalPool a -> a -> IO ()
destroyResource Pool resource
pool LocalPool resource
localPool resource
resource
            Either failure success -> IO (Either failure success)
forall (m :: * -> *) a. Monad m => a -> m a
return (failure -> Either failure success
forall a b. a -> Either a b
Left failure
failure)