{-# LANGUAGE TupleSections #-}

module Jerimum.PostgreSQL.Helper
  ( fetchAll
  , fetchColsData
  , fetchColsName
  ) where

import           Control.Monad
import qualified Data.ByteString           as B
import qualified Database.PostgreSQL.LibPQ as PQ

fetchColsData :: PQ.Result -> PQ.Row -> [PQ.Column] -> IO (Maybe [B.ByteString])
fetchColsData reply row ncols = sequence <$> mapM (PQ.getvalue' reply row) ncols

fetchColsName :: PQ.Result -> IO (Maybe [(PQ.Column, B.ByteString)])
fetchColsName reply = do
  ncols <- pred <$> PQ.nfields reply
  mcolnames <- sequence <$> mapM (PQ.fname reply) [0 .. ncols]
  pure (zip [0 .. ncols] <$> mcolnames)

fetchAll :: PQ.Result -> IO (Maybe ([B.ByteString], [[B.ByteString]]))
fetchAll reply = do
  nrows <- pred <$> PQ.ntuples reply
  mcols <- fetchColsName reply
  status <- PQ.resultStatus reply
  case (status, mcols) of
    (PQ.TuplesOk, Just cols) -> do
      mrows <-
        sequence <$>
        forM [0 .. nrows] (\row -> fetchColsData reply row (map fst cols))
      pure $ (map snd cols, ) <$> mrows
    _ -> pure Nothing
