module Hasql.Private.Session.UnliftIO where
import Control.Monad.Reader.Class (ask)
import Control.Monad.Error.Class (throwError)
import Control.Monad.IO.Unlift
import Control.Exception.Safe
import Hasql.Session
instance MonadUnliftIO Session where
withRunInIO :: forall b. ((forall a. Session a -> IO a) -> IO b) -> Session b
withRunInIO (forall a. Session a -> IO a) -> IO b
inner = do
Connection
conn <- Session Connection
forall r (m :: * -> *). MonadReader r m => m r
ask
Either SessionError b
res <- IO (Either SessionError b) -> Session (Either SessionError b)
forall a. IO a -> Session a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO (Either SessionError b) -> Session (Either SessionError b))
-> IO (Either SessionError b) -> Session (Either SessionError b)
forall a b. (a -> b) -> a -> b
$ IO b -> IO (Either SessionError b)
forall (m :: * -> *) e a.
(HasCallStack, MonadCatch m, Exception e) =>
m a -> m (Either e a)
try (IO b -> IO (Either SessionError b))
-> IO b -> IO (Either SessionError b)
forall a b. (a -> b) -> a -> b
$ (forall a. Session a -> IO a) -> IO b
inner ((forall a. Session a -> IO a) -> IO b)
-> (forall a. Session a -> IO a) -> IO b
forall a b. (a -> b) -> a -> b
$ \Session a
sess -> do
Session a -> Connection -> IO (Either SessionError a)
forall a. Session a -> Connection -> IO (Either SessionError a)
run Session a
sess Connection
conn IO (Either SessionError a)
-> (Either SessionError a -> IO a) -> IO a
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (SessionError -> IO a)
-> (a -> IO a) -> Either SessionError a -> IO a
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either SessionError -> IO a
forall (m :: * -> *) e a.
(HasCallStack, MonadThrow m, Exception e) =>
e -> m a
throwIO a -> IO a
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure
case Either SessionError b
res of
Left SessionError
e -> SessionError -> Session b
forall a. SessionError -> Session a
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError SessionError
e
Right b
a -> b -> Session b
forall a. a -> Session a
forall (f :: * -> *) a. Applicative f => a -> f a
pure b
a