on e548510 help sign in
rel8/src/Rel8/Tabulate.hs
385 lines 12 kB history raw
1{-# language DeriveFunctor #-}
2{-# language DerivingStrategies #-}
3{-# language FlexibleContexts #-}
4{-# language TupleSections #-}
5{-# language UndecidableInstances #-}
7module Rel8.Tabulate
8 ( Tabulation
9 , tabulate
10 , tabulateA
11 , runTabulation
12 , fromQuery
13 , liftQuery
14 , prebind
15 , postbind
16 , indexed
17 , ifilter
18 , lookup
19 , align
20 , alignWith
21 , leftAlign
22 , leftAlignWith
23 , zip
24 , zipWith
25 , similarity
26 , difference
27 , aggregateTabulation
28 , orderTabulation
29 , singularize
30 , optionalTabulation
31 , manyTabulation
32 , someTabulation
33 )
34where
36-- base
37import Control.Applicative ( liftA2 )
38import Control.Monad ( join, liftM2 )
39import Data.Bifunctor ( bimap, first )
40import Data.Foldable ( traverse_ )
41import Data.Functor.Contravariant ( (>$<) )
42import Data.Maybe ( fromMaybe )
43import Prelude hiding ( filter, lookup, zip, zipWith )
45-- rel8
46import Rel8.Aggregate ( Aggregate )
47import Rel8.Expr ( Expr )
48import Rel8.Order ( Order )
49import Rel8.Query ( Query )
50import Rel8.Query.Aggregate ( aggregate )
51import Rel8.Query.Exists ( withBy, withoutBy )
52import Rel8.Query.Filter ( filter, where_ )
53import Rel8.Query.Maybe ( optional )
54import Rel8.Query.Order ( orderBy )
55import Rel8.Query.These ( alignBy )
56import Rel8.Table ( Table )
57import Rel8.Table.Aggregate ( groupBy, headAgg, listAgg, nonEmptyAgg )
58import Rel8.Table.Alternative
59 ( AltTable, (<|>:)
60 , AlternativeTable, emptyTable
61 )
62import Rel8.Table.Eq ( EqTable, (==:) )
63import Rel8.Table.List ( ListTable )
64import Rel8.Table.Maybe ( MaybeTable, maybeTable )
65import Rel8.Table.NonEmpty ( NonEmptyTable )
66import Rel8.Table.These ( TheseTable, theseTable )
68-- semigroupoids
69import Data.Functor.Apply ( Apply, liftF2 )
70import Data.Functor.Bind ( Bind )
71import qualified Data.Functor.Bind
72import Data.Semigroup.Traversable.Class ( bitraverse1 )
75-- | @'Tabulation' k a@ is denotionally a @MultiMap k a@ — a @Map@ where each
76-- key @k@ corresponds to potentially multiple @a@ (i.e., @'Query' a@). This
77-- @MultiMap@ supports 'lookup' and other operations you would expect it to.
78--
79-- \"Identity\" 'Tabulation's are created using 'tabulate'. 'Tabulation's can
80-- be composed with 'Query's with 'prebind' or 'postbind' to form new
81-- 'Tabulation's.
82newtype Tabulation k a = Tabulation (k -> Query (Maybe k, a))
83 deriving stock Functor
86instance EqTable k => Apply (Tabulation k) where
87 liftF2 = liftA2
90instance EqTable k => Applicative (Tabulation k) where
91 pure = liftQuery . pure
92 liftA2 = liftM2
95instance EqTable k => Bind (Tabulation k) where
96 join = join
99instance EqTable k => Monad (Tabulation k) where
100 Tabulation as >>= f = Tabulation $ \i -> do
101 (mk, a) <- as i
102 case mk of
103 Nothing -> case f a of
104 Tabulation bs -> bs i
105 Just k -> case f a of
106 Tabulation bs -> do
107 (mk', b) <- bs k
108 case mk' of
109 Nothing -> pure (mk, b)
110 Just k' -> do
111 where_ $ k ==: k'
112 pure (mk', b)
115instance EqTable k => AltTable (Tabulation k) where
116 kas <|>: kbs = do
117 as <- toQuery kas
118 bs <- toQuery kbs
119 fromQuery $ as <|>: bs
122instance EqTable k => AlternativeTable (Tabulation k) where
123 emptyTable = fromQuery emptyTable
126instance (EqTable k, Table Expr a, Semigroup a) => Semigroup (Tabulation k a)
127 where
128 (<>) = alignWith (theseTable id id (<>))
131instance (EqTable k, Table Expr a, Semigroup a) => Monoid (Tabulation k a)
132 where
133 mempty = emptyTable
136runTabulation :: EqTable k => Query k -> Tabulation k a -> Query (k, a)
137runTabulation ks tabulation = do
138 k <- ks
139 a <- lookup k tabulation
140 pure (k, a)
143liftQuery :: Query a -> Tabulation k a
144liftQuery query = Tabulation $ const $ fmap (Nothing,) query
147-- | 'tabulate' creates an \"identity\" @'Tabulation' k a@ that allows @a@ be
148-- indexed by one or more of its columns @k@. Some examples:
149--
150-- [Tabulation by primary key]:
151-- @
152-- projectsById :: Project 'Expr' -> 'Tabulation' ('Expr' ProjectId) (Project 'Expr')
153-- projectsById = 'tabulate' projectId
154-- @
155--
156-- Note: the nature of primary keys means that each key will be mapped to a
157-- singleton value in this case.
158--
159-- [Tabulation by other unique key]:
160-- @
161-- projectsByName :: Project 'Expr' -> 'Tabulation' ('Expr' Text) (Project 'Expr')
162-- projectsByName = 'tabulate' projectName
163-- @
164--
165-- [Tabulation by foreign key (tabulate a child table by parent key)]:
166-- @
167-- revisionsByProjectId :: Revision 'Expr' -> 'Tabulation' ('Expr' ProjectId) (Revision 'Expr')
168-- revisionsByProjectId = 'tabulate' revisionProjectId
169-- @
170tabulate :: (a -> k) -> a -> Tabulation k a
171tabulate key a = fromQuery $ pure (key a, a)
174-- | Like 'tabulate' but takes a monadic 'Query' function instead of a pure
175-- one. This means you can filter rows while calculating the key, which is
176-- useful in conjunction with 'Rel8.Extra.catNulls'.
177tabulateA :: (a -> Query k) -> a -> Tabulation k a
178tabulateA key a = fromQuery $ (,a) <$> key a
181-- | Analgous to 'Data.Map.Strict.fromList'.
182fromQuery :: Query (k, a) -> Tabulation k a
183fromQuery = Tabulation . const . fmap (first Just)
186indexed :: Tabulation k a -> Tabulation k (k, a)
187indexed (Tabulation query) = Tabulation $ \i ->
188 (\(mk, a) -> (mk, (fromMaybe i mk, a))) <$> query i
191ifilter :: (k -> a -> Expr Bool) -> Tabulation k a -> Tabulation k a
192ifilter f tabulation = snd <$> do
193 filter (uncurry f) `postbind` indexed tabulation
196-- | Map a 'Query' over the input side of a 'Tabulation'.
197prebind :: (a -> Tabulation k b) -> Query a -> Tabulation k b
198prebind f as = Tabulation $ \k -> do
199 a <- as
200 case f a of
201 Tabulation query -> query k
202infixr 1 `prebind`
205-- | Map a 'Query' over the output side of a 'Tabulation'.
206postbind :: (a -> Query b) -> Tabulation k a -> Tabulation k b
207postbind f (Tabulation as) = Tabulation $ \i -> do
208 (k, a) <- as i
209 case f a of
210 bs -> do
211 b <- bs
212 pure (k, b)
213infixr 1 `postbind`
216-- | Note that because 'Tabulation' is a @MultiMap@, the 'Query' returned by
217-- 'lookup' can and often does contain multiple results.
218lookup :: EqTable k => k -> Tabulation k a -> Query a
219lookup key (Tabulation query) = do
220 (mk, a) <- query key
221 traverse_ (where_ . (key ==:)) mk
222 pure a
225-- | Analagous to
226-- [@align@](https://hackage.haskell.org/package/semialign/docs/Data-Semialign.html#v:align).
227--
228-- If 'zip' makes an @INNER JOIN@, then 'align' makes a @FULL OUTER JOIN@.
229align :: (EqTable k, Table Expr a, Table Expr b)
230 => Tabulation k a -> Tabulation k b -> Tabulation k (TheseTable a b)
231align = alignWith id
234-- | Analagous to
235-- [@alignWith@](https://hackage.haskell.org/package/semialign/docs/Data-Semialign.html#v:alignWith).
236--
237-- See 'zipWith' and 'align'.
238alignWith :: (EqTable k, Table Expr a, Table Expr b)
239 => (TheseTable a b -> c)
240 -> Tabulation k a -> Tabulation k b -> Tabulation k c
241alignWith f kas kbs = do
242 as <- toQuery kas
243 bs <- toQuery kbs
244 fromQuery $ do
245 tkab <- alignBy (\(l, _) (m, _) -> l ==: m) as bs
246 let
247 k' = theseTable fst fst (const fst) tkab
248 tab = bimap snd snd tkab
249 pure (k', f tab)
252-- | If 'zip' makes an @INNER JOIN@, then 'leftAlign' makes a @LEFT JOIN@.
253-- This means it will return at least one row for every row in the left
254-- 'Tabulation', even if there is no corresponding row in the right (hence the
255-- 'Rel8.MaybeTable').
256--
257-- Analagous to
258-- [@rpadZip@](https://hackage.haskell.org/package/semialign/docs/Data-Semialign.html#v:rpadZip).
259leftAlign :: EqTable k
260 => Tabulation k a -> Tabulation k b -> Tabulation k (a, MaybeTable b)
261leftAlign = leftAlignWith (,)
264-- | See 'zipWith' and 'leftAlign'.
265--
266-- Analagous to
267-- [@rpadZipWith@](https://hackage.haskell.org/package/semialign/docs/Data-Semialign.html#v:rpadZipWith).
268leftAlignWith :: EqTable k
269 => (a -> MaybeTable b -> c)
270 -> Tabulation k a -> Tabulation k b -> Tabulation k c
271leftAlignWith f left right = liftA2 f left (optionalTabulation right)
274-- | Analagous to
275-- [@zip@](https://hackage.haskell.org/package/semialign/docs/Data-Semialign.html#v:zip).
276--
277-- There are multiple correct ways of understanding what this does.
278--
279-- You can think of it as @'Data.Map.Strict.intersectionWith'
280-- ('Control.Applicative.liftA2' (,))@. That is, @intersect@ the two
281-- `Tabulation`s by matching their keys together (with 'Rel8.==:'), and combine
282-- their values (remembering that 'Tabulation' is a 'MultiMap' so that the
283-- values are keys) by getting their cartesian product.
284--
285-- You can think of it as performing a cross product of the underlying 'Query's
286-- of the given 'Tabulation's and filtering the results for 'match'ing keys.
287--
288-- You can think of it as a natural join in SQL terms.
289--
290-- The size of the resulting 'Tabulation' will be \(\sum_{k} min(n_k, m_k) \)
291-- in terms of the number of keys, but \(\sum_{k} n_k \times m_k\) in terms of
292-- the number of values.
293zip :: EqTable k
294 => Tabulation k a -> Tabulation k b -> Tabulation k (a, b)
295zip = zipWith (,)
298-- | Analagous to
299-- [@zipWith@](https://hackage.haskell.org/package/semialign/docs/Data-Semialign.html#v:zipWith).
300--
301-- See 'zip'.
302zipWith :: EqTable k
303 => (a -> b -> c) -> Tabulation k a -> Tabulation k b -> Tabulation k c
304zipWith = liftA2
307-- | 'similarity' returns all the entries in the left 'Tabulation' that have a
308-- corresponding entry in the right 'Tabulation'. This corresponds to a
309-- semijoin in relational algebra.
310--
311-- This differs from @'zipWith' const x y@ when the right 'Tabulation' @y@
312-- contains an entry with multiple rows. For 'similarity', the entries in the
313-- resulting 'Tabulation' will contain the same number of rows as their
314-- respective entries in the left 'Tabulation' @x@. With `zipWith const x y`,
315-- each entry would contain the /product/ of the number of rows of their
316-- respective entries in @x@ and @y@.
317--
318-- See 'Rel8.with'.
319similarity :: EqTable k => Tabulation k a -> Tabulation k b -> Tabulation k a
320similarity kas kbs = do
321 as <- toQuery kas
322 bs <- toQuery kbs
323 fromQuery $ as >>= withBy (\(k, _) (l, _) -> k ==: l) bs
326-- | 'difference' returns all the entries in the left 'Tabulation' that don't
327-- exist in the right 'Tabulation'. This corresponds to an antijoin in
328-- relational algebra.
329--
330-- See 'Rel8.without'.
331difference :: EqTable k => Tabulation k a -> Tabulation k b -> Tabulation k a
332difference kas kbs = do
333 as <- toQuery kas
334 bs <- toQuery kbs
335 fromQuery $ as >>= withoutBy (\(k, _) (l, _) -> k ==: l) bs
338aggregateTabulation :: EqTable k
339 => Tabulation k (Aggregate a) -> Tabulation k a
340aggregateTabulation kas = do
341 as <- toQuery kas
342 fromQuery $ aggregate $ bitraverse1 groupBy id <$> as
345-- | 'orderTabulation' orders the /values/ of a 'Tabulation' (not the keys).
346-- In general this is meaningless, but if used together with 'manyTabulation'
347-- or 'someTabulation', the resulting lists will be ordered according to
348-- ordering given to 'orderTabulation'.
349orderTabulation :: Order a -> Tabulation k a -> Tabulation k a
350orderTabulation ordering (Tabulation as) =
351 Tabulation $ orderBy (snd >$< ordering) . as
354-- | Turns the given 'Tabulation' from a \"multimap\" into a \"map\". If there
355-- is more than one value at a particular key, only the first one is kept.
356-- \"First\" is in general undefined, but 'orderTabulation' can be used to
357-- make it deterministic.
358singularize :: (EqTable k, Table Expr a) => Tabulation k a -> Tabulation k a
359singularize = aggregateTabulation . fmap headAgg
362optionalTabulation :: EqTable k
363 => Tabulation k a -> Tabulation k (MaybeTable a)
364optionalTabulation as = Tabulation $ \k -> do
365 ma <- optional $ lookup k as
366 pure (Just k, ma)
369manyTabulation :: (EqTable k, Table Expr a)
370 => Tabulation k a -> Tabulation k (ListTable a)
371manyTabulation =
372 fmap (maybeTable mempty id) .
373 optionalTabulation .
374 aggregateTabulation .
375 fmap listAgg
378someTabulation :: (EqTable k, Table Expr a)
379 => Tabulation k a -> Tabulation k (NonEmptyTable a)
380someTabulation = aggregateTabulation . fmap nonEmptyAgg
383toQuery :: Tabulation k a -> Tabulation k (Query (k, a))
384toQuery (Tabulation as) = Tabulation $ \k ->
385 pure (Nothing, first (fromMaybe k) <$> as k)