Răzvan Flavius Panda
Răzvan Flavius Panda

Reputation: 22106

Haskell Esqueleto project to list of records instead of tuples

In all the examples I have seen the results from esqueleto are projected into a list of tuples. This makes coding and maintenance harder because of lack of labels.

For example:

previousLogItems <- select $ from $ \li -> do
        orderBy [desc (li ^. LogItemId)]
        limit 10
        return (li ^. LogItemId, li ^. LogItemTitle)

Is there any way to get esqueleto to project the results to a list of records instead?

Upvotes: 1

Views: 200

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476574

In fact you construct the tuple yourself. Indeed:

previousLogItems <- select $ from $ \li -> do
        orderBy [desc (li ^. LogItemId)]
        limit 10
        return (li ^. LogItemId, li ^. LogItemTitle)

You thus make use of the (^.) :: (PersistEntity val, PersistField typ) => expr (Entity val) -> EntityField val typ -> expr (Value typ) "selector" to obtain the fields and wrap them into a tuple.

If you write it like:

previousLogItems >- select $ from $ \li -> do
        orderBy [desc (li ^. LogItemId)]
        limit 10
        return li

You will obtain a list of [Entity Foo] where Foo is the type of object you query.

You can use the entityVal :: Entity a -> a to obtain the entity that is wrapped into the Entity, for example:

previousLogItems <- select $ from $ \li -> do
        orderBy [desc (li ^. LogItemId)]
        limit 10
        return li
mapM_ (print . entityVal) previousLogItems

given the entity is of course an instance of Show.

Upvotes: 4

Related Questions