on 28aaa76 help sign in
rel8/src/Rel8/Table/Aggregate.hs
69 lines 2.4 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 )
13where
15-- base
16import Data.Functor.Identity ( Identity( Identity ) )
17import Prelude
19-- rel8
20import Rel8.Aggregate ( Aggregate, Col(..) )
21import Rel8.Expr ( Expr, Col(..) )
22import Rel8.Expr.Aggregate ( groupByExpr, listAggExpr, nonEmptyAggExpr )
23import Rel8.Schema.Dict ( Dict( Dict ) )
24import Rel8.Schema.HTable ( htabulate, hfield )
25import Rel8.Schema.HTable.Vectorize ( hvectorize )
26import Rel8.Table ( Table, toColumns, fromColumns )
27import Rel8.Table.Eq ( EqTable, eqTable )
28import Rel8.Table.List ( ListTable )
29import Rel8.Table.NonEmpty ( NonEmptyTable )
32-- | Group equal tables together. This works by aggregating each column in the
33-- given table with 'groupByExpr'.
34groupBy :: forall exprs. EqTable exprs => exprs -> Aggregate exprs
35groupBy (toColumns -> exprs) = fromColumns $ htabulate $ \field ->
36 case hfield (eqTable @exprs) field of
37 Dict -> case hfield exprs field of
38 DB expr -> Aggregation $ groupByExpr expr
41-- | Aggregate rows into a single row containing an array of all aggregated
42-- rows. This can be used to associate multiple rows with a single row, without
43-- changing the over cardinality of the query. This allows you to essentially
44-- return a tree-like structure from queries.
45--
46-- For example, if we have a table of orders and each orders contains multiple
47-- items, we could aggregate the table of orders, pairing each order with its
48-- items:
49--
50-- @
51-- ordersWithItems :: Query (Order Expr, ListTable (Item Expr))
52-- ordersWithItems = do
53-- order <- each orderSchema
54-- items <- aggregate $ listAgg <$> itemsFromOrder order
55-- return (order, items)
56-- @
57listAgg :: Table Expr exprs => exprs -> Aggregate (ListTable exprs)
58listAgg (toColumns -> exprs) = fromColumns $
59 hvectorize
60 (\_ (Identity (DB a)) -> Aggregation $ listAggExpr a)
61 (pure exprs)
64-- | Like 'listAgg', but the result is guaranteed to be a non-empty list.
65nonEmptyAgg :: Table Expr exprs => exprs -> Aggregate (NonEmptyTable exprs)
66nonEmptyAgg (toColumns -> exprs) = fromColumns $
67 hvectorize
68 (\_ (Identity (DB a)) -> Aggregation $ nonEmptyAggExpr a)
69 (pure exprs)