1{-# language FlexibleContexts #-}
2{-# language NamedFieldPuns #-}
3{-# language ScopedTypeVariables #-}
4{-# language TypeApplications #-}
5{-# language TypeFamilies #-}
6{-# language ViewPatterns #-}
8module Rel8.Table.Aggregate
16import Data.Functor.Identity ( Identity( Identity ) )
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.
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
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)
57listAgg :: Table Expr exprs => exprs -> Aggregate (ListTable exprs)
58listAgg (toColumns -> exprs) = fromColumns $
60 (\_ (Identity (DB a)) -> Aggregation $ listAggExpr a)
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 $
68 (\_ (Identity (DB a)) -> Aggregation $ nonEmptyAggExpr a)
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list