Skip to content

Instantly share code, notes, and snippets.

@benkolera
Last active August 31, 2015 07:10
Show Gist options
  • Save benkolera/22a2833f73aa20903f20 to your computer and use it in GitHub Desktop.
Save benkolera/22a2833f73aa20903f20 to your computer and use it in GitHub Desktop.
ILY Opaleye
data Pagination = Pagination
{ _paginationPage :: Int
, _paginationWidth :: Int
}
makeLenses ''Pagination
data PaginationResults a = PaginationResults
{ _paginationResultsPage :: Int
, _paginationResultsWidth :: Int
, _paginationResultsMaxPage :: Int64
, _paginationResultsRows :: [a]
} deriving (Show,Functor)
makeLenses ''PaginationResults
paginateQuery :: Pagination -> Query a -> Query a
paginateQuery (Pagination p w) = limit w . offset ((p-1) * w)
countQuery :: (a -> Column i) -> Query a -> Query (Column PGInt8)
countQuery getId = aggregate count . fmap getId
paginationResults :: Pagination -> Maybe Int64 -> [a] -> PaginationResults a
paginationResults (Pagination pw pp) cMay res = PaginationResults pp pw pm res
where pm = maybe 0 (\c -> ceiling (fromIntegral (c::Int64) / fromIntegral pw)) cMay
paginate
:: (CanOpaleye c e m, Default QueryRunner a b)
=> Pagination
-> (a -> Column i)
-> Query a
-> m (PaginationResults b)
paginate p getId q = paginationResults p
<$> liftQueryFirst (countQuery getId q)
<*> liftQuery (paginateQuery p q)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment