lpsmith / postgresql-simple

Mid-level client library for accessing PostgreSQL from Haskell
Other
206 stars 71 forks source link

add support for aggregate functions #148

Closed levinotik closed 9 years ago

levinotik commented 9 years ago

Wondering if there's a sensible way to add support for aggregate functions so that certain queries could return a single result instead of [r]. (Perhaps it would need to be Maybe r?)

levinotik commented 9 years ago

I'm still pretty new to Haskell...maybe this is best handled by just using listToMaybe and doesn't need to be in the library?

sopvop commented 9 years ago

Aggregate functions still return you rows. If you expect a single row or nothing, then just use something like

headMay :: [a] -> Maybe a
headMay [] = Nothing
headMay (x:_) = Just x

note :: e -> Maybe a -> Either e a
note e = maybe (Left e) Right

maybeQuery :: FromRow r => IO (Maybe r)
maybeQuery = fmap headMay $ query_ "select * from some_table where primary_key = 1;"

eitherQuery :: FromRow r => IO (Either String r)
eitherQuery = note "Empty result set, impossible!!" . headMay <$> query_ "select count(*) from some_table"

headMay and note with many other handy combinators are inerrors package.

levinotik commented 9 years ago

@sopvop thanks a lot, really appreciate it

cimmanon commented 9 years ago

@sopvop listToMaybe already does that, no need to roll your own.

singleItem :: FromRow r => IO (Maybe r)
singleItem = listToMaybe <$> query_ "select * from some_table where primary_key = 1;"

A maybeToEither function already exists as well.

sopvop commented 9 years ago

I just like names in errors package :-)