opaleye-0.5.0.0: An SQL-generating DSL targeting PostgreSQL

Safe HaskellNone
LanguageHaskell98

Opaleye.Internal.Aggregate

Synopsis

Documentation

newtype Aggregator a b Source

An Aggregator takes a collection of rows of type a, groups them, and transforms each group into a single row of type b. This corresponds to aggregators using GROUP BY in SQL.

An Aggregator corresponds closely to a Fold from the foldl package. Whereas an Aggregator a b takes each group of type a to a single row of type b, a Fold a b takes a list of a and returns a single row of type b.

orderAggregate :: Order a -> Aggregator a b -> Aggregator a b Source

Order the values within each aggregation in Aggregator using the given ordering. This is only relevant for aggregations that depend on the order they get their elements, like arrayAgg and stringAgg.

You can either apply it to an aggregation of multiple columns, in which case it will apply to all aggregation functions in there, or you can apply it to a single column, and then compose the aggregations afterwards. Examples:

x :: Aggregator (Column a, Column b) (Column (PGArray a), Column (PGArray a))
x = (,) <$> orderAggregate (asc snd) (lmap fst arrayAggGrouped)
        <*> orderAggregate (desc snd) (lmap fst arrayAggGrouped)

This will generate:

SELECT array_agg(a ORDER BY b ASC), array_agg(a ORDER BY b DESC)
FROM (SELECT a, b FROM ...)

Or:

x :: Aggregator (Column a, Column b) (Column (PGArray a), Column (PGArray b))
x = orderAggregate (asc snd) $ p2 (arrayAggGrouped, arrayAggGrouped)

This will generate:

SELECT array_agg(a ORDER BY b ASC), array_agg(b ORDER BY b ASC)
FROM (SELECT a, b FROM ...)