1{-# language FlexibleContexts #-}
2{-# language NamedFieldPuns #-}
3{-# language ScopedTypeVariables #-}
4{-# language TypeApplications #-}
5{-# language TypeFamilies #-}
6{-# language ViewPatterns #-}
8module Rel8.Table.Aggregate
17import Data.Functor.Identity ( Identity( Identity ) )
21import Rel8.Aggregate ( Aggregate, Aggregates, Col(..) )
22import Rel8.Expr ( Expr, Col(..) )
23import Rel8.Expr.Aggregate ( listAggExpr, nonEmptyAggExpr, sgroupByExpr )
24import Rel8.Schema.Dict ( Dict( Dict ) )
25import Rel8.Schema.HTable ( htabulate, hfield, hdicts, hspecs )
26import Rel8.Schema.HTable.Vectorize ( hvectorize )
27import Rel8.Schema.Spec ( SSpec(..) )
28import Rel8.Schema.Spec.ConstrainDBType ( ConstrainDBType )
29import Rel8.Table ( Table, Columns, toColumns, fromColumns )
30import Rel8.Table.Eq ( EqTable )
31import Rel8.Table.List ( ListTable )
32import Rel8.Table.NonEmpty ( NonEmptyTable )
33import Rel8.Type.Eq ( DBEq )
36-- | Group equal tables together. This works by aggregating each column in the
37-- given table with 'groupByExpr'.
38groupBy :: forall exprs. EqTable exprs => exprs -> Aggregate exprs
39groupBy (toColumns -> exprs) = fromColumns $ htabulate $ \field ->
40 case hfield dicts field of
41 Dict -> case hfield hspecs field of
42 SSpec {nullability} -> case hfield exprs field of
43 DB expr -> Aggregation $ sgroupByExpr nullability expr
45 dicts = hdicts @(Columns exprs) @(ConstrainDBType DBEq)
48-- | Aggregate rows into a single row containing an array of all aggregated
49-- rows. This can be used to associate multiple rows with a single row, without
50-- changing the over cardinality of the query. This allows you to essentially
51-- return a tree-like structure from queries.
53-- For example, if we have a table of orders and each orders contains multiple
54-- items, we could aggregate the table of orders, pairing each order with its
58-- ordersWithItems :: Query (Order Expr, ListTable (Item Expr))
59-- ordersWithItems = do
60-- order <- each orderSchema
61-- items <- aggregate $ listAgg <$> itemsFromOrder order
62-- return (order, items)
64listAgg :: Table Expr exprs => exprs -> Aggregate (ListTable exprs)
65listAgg (toColumns -> exprs) = fromColumns $
67 (\_ (Identity (DB a)) -> Aggregation $ listAggExpr a)
71-- | Like 'listAgg', but the result is guaranteed to be a non-empty list.
72nonEmptyAgg :: Table Expr exprs => exprs -> Aggregate (NonEmptyTable exprs)
73nonEmptyAgg (toColumns -> exprs) = fromColumns $
75 (\_ (Identity (DB a)) -> Aggregation $ nonEmptyAggExpr a)
79runAggregation :: Aggregates aggregates exprs => aggregates -> Aggregate exprs
80runAggregation = fromColumns . toColumns
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