Add Maybe as possible row container type
This commit is contained in:
@@ -47,16 +47,20 @@ import Database.PostgreSQL.Opium.ToField (ToField (..))
|
||||
import Database.PostgreSQL.Opium.ToParamList (ToParamList (..))
|
||||
|
||||
class RowContainer c where
|
||||
extract :: FromRow a => Result -> ColumnTable -> ExceptT Error IO (c a)
|
||||
extract :: FromRow a => Result -> LibPQ.Row -> ColumnTable -> ExceptT Error IO (c a)
|
||||
|
||||
instance RowContainer [] where
|
||||
extract result columnTable = do
|
||||
nRows <- liftIO $ LibPQ.ntuples result
|
||||
extract result nRows columnTable = do
|
||||
mapM (ExceptT . fromRow result columnTable) [0..nRows - 1]
|
||||
|
||||
instance RowContainer Maybe where
|
||||
extract result nRows columnTable
|
||||
| nRows == 0 = pure Nothing
|
||||
| nRows == 1 = Just <$> ExceptT (fromRow result columnTable 0)
|
||||
| otherwise = throwE ErrorMoreThanOneRow
|
||||
|
||||
instance RowContainer Identity where
|
||||
extract result columnTable = do
|
||||
nRows <- liftIO $ LibPQ.ntuples result
|
||||
extract result nRows columnTable = do
|
||||
unless (nRows == 1) $ throwE ErrorNotExactlyOneRow
|
||||
Identity <$> ExceptT (fromRow result columnTable 0)
|
||||
|
||||
@@ -69,8 +73,9 @@ fetch
|
||||
-> IO (Either Error (b a))
|
||||
fetch query params conn = runExceptT $ do
|
||||
result <- execParams conn query params
|
||||
nRows <- liftIO $ LibPQ.ntuples result
|
||||
columnTable <- ExceptT $ getColumnTable @a Proxy result
|
||||
extract result columnTable
|
||||
extract result nRows columnTable
|
||||
|
||||
fetch_ :: forall a c. (FromRow a, RowContainer c) => Text -> Connection -> IO (Either Error (c a))
|
||||
fetch_ query = fetch query ()
|
||||
|
||||
@@ -18,6 +18,7 @@ data Error
|
||||
| ErrorUnexpectedNull ErrorPosition
|
||||
| ErrorInvalidField ErrorPosition Oid ByteString String
|
||||
| ErrorNotExactlyOneRow
|
||||
| ErrorMoreThanOneRow
|
||||
deriving (Eq, Show)
|
||||
|
||||
instance Exception Error where
|
||||
|
||||
Reference in New Issue
Block a user