on 0b34a14 help sign in
rel8/src/Rel8/Table/Aggregate.hs
78 lines 2.7 kB history raw
1{-# language FlexibleContexts #-}
2{-# language NamedFieldPuns #-}
3{-# language ScopedTypeVariables #-}
4{-# language TypeApplications #-}
5{-# language TypeFamilies #-}
6{-# language ViewPatterns #-}
8module Rel8.Table.Aggregate
9 ( groupBy
10 , listAgg
11 , nonEmptyAgg
12 , runAggregation
13 )
14where
16-- base
17import Data.Functor.Identity ( Identity( Identity ) )
18import Prelude
20-- rel8
21import Rel8.Aggregate ( Aggregate, Aggregates, Col(..) )
22import Rel8.Expr ( Expr, Col(..) )
23import Rel8.Expr.Aggregate ( groupByExpr, listAggExpr, nonEmptyAggExpr )
24import Rel8.Schema.Dict ( Dict( Dict ) )
25import Rel8.Schema.HTable ( htabulate, hfield, hdicts )
26import Rel8.Schema.HTable.Vectorize ( hvectorize )
27import Rel8.Schema.Spec.ConstrainDBType ( ConstrainDBType )
28import Rel8.Table ( Table, Columns, toColumns, fromColumns )
29import Rel8.Table.Eq ( EqTable )
30import Rel8.Table.List ( ListTable )
31import Rel8.Table.NonEmpty ( NonEmptyTable )
32import Rel8.Type.Eq ( DBEq )
35-- | Group equal tables together. This works by aggregating each column in the
36-- given table with 'groupByExpr'.
37groupBy :: forall exprs. EqTable exprs => exprs -> Aggregate exprs
38groupBy (toColumns -> exprs) = fromColumns $ htabulate $ \field ->
39 case hfield dicts field of
40 Dict -> case hfield exprs field of
41 DB expr -> Aggregation $ groupByExpr expr
42 where
43 dicts = hdicts @(Columns exprs) @(ConstrainDBType DBEq)
46-- | Aggregate rows into a single row containing an array of all aggregated
47-- rows. This can be used to associate multiple rows with a single row, without
48-- changing the over cardinality of the query. This allows you to essentially
49-- return a tree-like structure from queries.
50--
51-- For example, if we have a table of orders and each orders contains multiple
52-- items, we could aggregate the table of orders, pairing each order with its
53-- items:
54--
55-- @
56-- ordersWithItems :: Query (Order Expr, ListTable (Item Expr))
57-- ordersWithItems = do
58-- order <- each orderSchema
59-- items <- aggregate $ listAgg <$> itemsFromOrder order
60-- return (order, items)
61-- @
62listAgg :: Table Expr exprs => exprs -> Aggregate (ListTable exprs)
63listAgg (toColumns -> exprs) = fromColumns $
64 hvectorize
65 (\_ (Identity (DB a)) -> Aggregation $ listAggExpr a)
66 (pure exprs)
69-- | Like 'listAgg', but the result is guaranteed to be a non-empty list.
70nonEmptyAgg :: Table Expr exprs => exprs -> Aggregate (NonEmptyTable exprs)
71nonEmptyAgg (toColumns -> exprs) = fromColumns $
72 hvectorize
73 (\_ (Identity (DB a)) -> Aggregation $ nonEmptyAggExpr a)
74 (pure exprs)
77runAggregation :: Aggregates aggregates exprs => aggregates -> Aggregate exprs
78runAggregation = fromColumns . toColumns