{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Preql.Wire.Internal where
import Preql.Wire.Errors
import Control.Monad.Trans.Except
import Control.Monad.Trans.State
import Data.String (IsString)
import Preql.Imports
import qualified Database.PostgreSQL.LibPQ as PQ
newtype Query = Query ByteString
deriving (Show, IsString)
data RowDecoder a = RowDecoder [PQ.Oid] (InternalDecoder a)
deriving Functor
instance Applicative RowDecoder where
pure a = RowDecoder [] (pure a)
RowDecoder t1 p1 <*> RowDecoder t2 p2 = RowDecoder (t1 <> t2) (p1 <*> p2)
type InternalDecoder = StateT DecoderState (ExceptT FieldError IO)
data DecoderState = DecoderState
{ result :: PQ.Result
, row :: PQ.Row
, column :: PQ.Column
} deriving (Show, Eq)
decodeRow :: RowDecoder a -> PQ.Result -> PQ.Row -> ExceptT FieldError IO a
decodeRow (RowDecoder _ parsers) result row =
evalStateT parsers (DecoderState result row 0)
getNextValue :: InternalDecoder (Maybe ByteString)
getNextValue = do
s@DecoderState{..} <- get
put (s { column = column + 1 } :: DecoderState)
liftIO $ PQ.getvalue result row column