HORIZON HASKELLDocslts/ghc-10.0.x8c2f8e82026-10-19Search names, modules, packages, or :: a typeCtrl K

GHC 10.0.0.20260917 · lts/ghc-10.0.x · 8c2f8e8 · 2026-10-19

Moduleopaleye-0.10.8.0Haskell2010

Opaleye.Aggregate

Perform aggregation on Selects. To aggregate a Select you should construct an Aggregator encoding how you want the aggregation to proceed, then call aggregate on it. The Aggregator should be constructed from the basic Aggregators below by using the combining operations from Data.Profunctor.Product.

  • 1 type
  • 22 values
  • Packageopaleye-0.10.8.0
  • Exports23
  • LanguageHaskell2010
  • LicenceBSD-3-Clause
  • SourceAggregate.hs

Aggregation

5 declarations
valueaggregate
  1. :: Default Unpackspec a a
  2. => Aggregator a b
  3. -> Select a
  4. -> Select b
#

Given a Select producing rows of type a and an Aggregator accepting rows of type a, apply the aggregator to the select.

If you simply want to count the number of rows in a query you might find the countRows function more convenient.

If you want to use aggregate with SelectArrs then you should compose it with Opaleye.Lateral.laterally:

Opaleye.Lateral.laterally . aggregate :: Aggregator a b -> SelectArr a b -> SelectArr a b

Please note that when aggregating an empty query with no GROUP BY clause, Opaleye's behaviour differs from Postgres's behaviour. Postgres returns a single row whereas Opaleye returns zero rows. Opaleye's behaviour is consistent with the meaning of aggregating over groups of rows and Postgres's behaviour is inconsistent. When a query has zero rows it has zero groups, and thus zero rows in the result of an aggregation.

newtypenewtype Aggregator a b
#

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.

You should combine basic Aggregators into Aggregators on compound types by using the operations in Data.Profunctor.Product.

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 value of type b.

Instances5Profunctor, ProductProfunctor, SumProfunctor, Functor, Applicative

Basic Aggregators

16 declarations

Aggregates values as a JSON array. An example usage:

import qualified Opaleye as O

O.aggregate O.jsonAgg $ do
    (firstCol, secondCol) <- O.selectTable table6
    return
      . O.jsonBuildObject
      $ O.jsonBuildObjectField "summary" firstCol
        <> O.jsonBuildObjectField "details" secondCol

The above query, when executed, will return JSON of the following form from postgres:

"[{\"summary\" : \"xy\", \"details\" : \"a\"}, {\"summary\" : \"z\", \"details\" : \"a\"}, {\"summary\" : \"more text\", \"details\" : \"a\"}]"

Counting rows

1 declaration

Explicit

1 declaration