on 06f34d2 help sign in
rel8/src/Rel8/Tabulate.hs
397 lines 13 kB history raw
1{-# language DeriveFunctor #-}
2{-# language DerivingStrategies #-}
3{-# language FlexibleContexts #-}
4{-# language LambdaCase #-}
5{-# language TupleSections #-}
6{-# language UndecidableInstances #-}
8module Rel8.Tabulate
9 ( Tabulation
10 , runTabulation
11 , tabulate
12 , tabulateA
13 , fromQuery
14 , liftQuery
15 , prebind
16 , postbind
17 , indexed
18 , ifilter
19 , lookup
20 , align
21 , alignWith
22 , leftAlign
23 , leftAlignWith
24 , zip
25 , zipWith
26 , similarity
27 , difference
28 , aggregateTabulation
29 , orderTabulation
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, undefined, zip, zipWith )
45-- rel8
46import Rel8.Aggregate ( Aggregate )
47import Rel8.Expr ( Expr )
48import Rel8.Expr.Bool ( not_, true )
49import Rel8.Order ( Order )
50import Rel8.Query ( Query )
51import Rel8.Query.Aggregate ( aggregate )
52import Rel8.Query.Exists ( withBy, withoutBy )
53import Rel8.Query.Filter ( filter, where_ )
54import Rel8.Query.Maybe ( optional )
55import Rel8.Query.Order ( orderBy )
56import Rel8.Query.These ( alignBy )
57import Rel8.Table ( Table )
58import Rel8.Table.Aggregate ( groupBy, listAgg, nonEmptyAgg )
59import Rel8.Table.Alternative
60 ( AltTable, (<|>:)
61 , AlternativeTable, emptyTable
62 )
63import Rel8.Table.Eq ( EqTable, (==:) )
64import Rel8.Table.List ( ListTable )
65import Rel8.Table.Maybe ( MaybeTable, maybeTable )
66import Rel8.Table.NonEmpty ( NonEmptyTable )
67import Rel8.Table.These ( TheseTable, theseTable )
68import Rel8.Table.Undefined ( undefined )
70-- semigroupoids
71import Data.Functor.Apply ( Apply, liftF2 )
72import Data.Functor.Bind ( Bind )
73import qualified Data.Functor.Bind
74import Data.Semigroup.Traversable.Class ( bitraverse1 )
77-- | @'Tabulation' k a@ is denotionally a @MultiMap k a@ — a @Map@ where each
78-- key @k@ corresponds to potentially multiple @a@ (i.e., @'Query' a@). This
79-- @MultiMap@ supports 'lookup' and other operations you would expect it to.
80--
81-- \"Identity\" 'Tabulation's are created using 'tabulate'. 'Tabulation's can
82-- be composed with 'Query's with 'prebind' or 'postbind' to form new
83-- 'Tabulation's.
84newtype Tabulation k a = Tabulation (Either k k -> Query (Maybe k, a))
85 deriving stock Functor
88instance EqTable k => Apply (Tabulation k) where
89 liftF2 = liftA2
92instance EqTable k => Applicative (Tabulation k) where
93 pure = liftQuery . pure
94 liftA2 = liftM2
97instance EqTable k => Bind (Tabulation k) where
98 join = join
101instance EqTable k => Monad (Tabulation k) where
102 Tabulation as >>= f = Tabulation $ \i -> do
103 (mk, a) <- as i
104 case mk of
105 Nothing -> case f a of
106 Tabulation bs -> bs i
107 Just k -> case f a of
108 Tabulation bs -> do
109 (mk', b) <- bs (Right k)
110 case mk' of
111 Nothing -> pure (mk, b)
112 Just k' -> do
113 where_ $ k ==: k'
114 pure (mk', b)
117instance EqTable k => AltTable (Tabulation k) where
118 kas <|>: kbs = do
119 as <- toQuery kas
120 bs <- toQuery kbs
121 fromQuery $ as <|>: bs
124instance EqTable k => AlternativeTable (Tabulation k) where
125 emptyTable = fromQuery emptyTable
128instance (EqTable k, Table Expr a, Semigroup a) => Semigroup (Tabulation k a)
129 where
130 (<>) = alignWith (theseTable id id (<>))
133instance (EqTable k, Table Expr a, Semigroup a) => Monoid (Tabulation k a)
134 where
135 mempty = emptyTable
138-- | This "undoes" 'fromQuery'.
139--
140-- @
141-- 'runTabulation' . 'fromQuery' = id
142-- 'fromQuery' . 'runTabulation' = id
143-- @
144--
145-- Note however that it produces nonsense when passed a 'Tabulation' that was
146-- made with from 'liftQuery' or 'pure'. In such cases the returned 'Query'
147-- will always produce zero rows.
148runTabulation :: EqTable k => Tabulation k a -> Query (k, a)
149runTabulation (Tabulation f) = do
150 (mk, a) <- f (Left undefined)
151 case mk of
152 Nothing -> do
153 -- Opaleye tries to be too clever optimising "WHERE FALSE" and generates
154 -- invalid SQL, so we use "WHERE NOT TRUE" instead
155 where_ $ not_ true
156 pure (undefined, a)
157 Just k -> pure (k, a)
160liftQuery :: Query a -> Tabulation k a
161liftQuery query = Tabulation $ const $ fmap (Nothing,) query
164-- | 'tabulate' creates an \"identity\" @'Tabulation' k a@ that allows @a@ be
165-- indexed by one or more of its columns @k@. Some examples:
166--
167-- [Tabulation by primary key]:
168-- @
169-- projectsById :: Project 'Expr' -> 'Tabulation' ('Expr' ProjectId) (Project 'Expr')
170-- projectsById = 'tabulate' projectId
171-- @
172--
173-- Note: the nature of primary keys means that each key will be mapped to a
174-- singleton value in this case.
175--
176-- [Tabulation by other unique key]:
177-- @
178-- projectsByName :: Project 'Expr' -> 'Tabulation' ('Expr' Text) (Project 'Expr')
179-- projectsByName = 'tabulate' projectName
180-- @
181--
182-- [Tabulation by foreign key (tabulate a child table by parent key)]:
183-- @
184-- revisionsByProjectId :: Revision 'Expr' -> 'Tabulation' ('Expr' ProjectId) (Revision 'Expr')
185-- revisionsByProjectId = 'tabulate' revisionProjectId
186-- @
187tabulate :: (a -> k) -> a -> Tabulation k a
188tabulate key a = fromQuery $ pure (key a, a)
191-- | Like 'tabulate' but takes a monadic 'Query' function instead of a pure
192-- one. This means you can filter rows while calculating the key, which is
193-- useful in conjunction with 'Rel8.Extra.catNulls'.
194tabulateA :: (a -> Query k) -> a -> Tabulation k a
195tabulateA key a = fromQuery $ (,a) <$> key a
198-- | Analgous to 'Data.Map.Strict.fromList'.
199fromQuery :: Query (k, a) -> Tabulation k a
200fromQuery = Tabulation . const . fmap (first Just)
203indexed :: Tabulation k a -> Tabulation k (k, a)
204indexed (Tabulation query) = Tabulation $ \i ->
205 (\(mk, a) -> (mk, (fromMaybe (either id id i) mk, a))) <$> query i
208ifilter :: (k -> a -> Expr Bool) -> Tabulation k a -> Tabulation k a
209ifilter f tabulation = snd <$> do
210 filter (uncurry f) `postbind` indexed tabulation
213-- | Map a 'Query' over the input side of a 'Tabulation'.
214prebind :: (a -> Tabulation k b) -> Query a -> Tabulation k b
215prebind f as = Tabulation $ \k -> do
216 a <- as
217 case f a of
218 Tabulation query -> query k
219infixr 1 `prebind`
222-- | Map a 'Query' over the output side of a 'Tabulation'.
223postbind :: (a -> Query b) -> Tabulation k a -> Tabulation k b
224postbind f (Tabulation as) = Tabulation $ \i -> do
225 (k, a) <- as i
226 case f a of
227 bs -> do
228 b <- bs
229 pure (k, b)
230infixr 1 `postbind`
233-- | Note that because 'Tabulation' is a @MultiMap@, the 'Query' returned by
234-- 'lookup' can and often does contain multiple results.
235lookup :: EqTable k => k -> Tabulation k a -> Query a
236lookup key (Tabulation query) = do
237 (mk, a) <- query (Right key)
238 traverse_ (where_ . (key ==:)) mk
239 pure a
242-- | Analagous to
243-- [@align@](https://hackage.haskell.org/package/semialign/docs/Data-Semialign.html#v:align).
244--
245-- If 'zip' makes an @INNER JOIN@, then 'align' makes a @FULL OUTER JOIN@.
246align :: (EqTable k, Table Expr a, Table Expr b)
247 => Tabulation k a -> Tabulation k b -> Tabulation k (TheseTable a b)
248align = alignWith id
251-- | Analagous to
252-- [@alignWith@](https://hackage.haskell.org/package/semialign/docs/Data-Semialign.html#v:alignWith).
253--
254-- See 'zipWith' and 'align'.
255alignWith :: (EqTable k, Table Expr a, Table Expr b)
256 => (TheseTable a b -> c)
257 -> Tabulation k a -> Tabulation k b -> Tabulation k c
258alignWith f kas kbs = do
259 as <- toQuery kas
260 bs <- toQuery kbs
261 fromQuery $ do
262 tkab <- alignBy (\(l, _) (m, _) -> l ==: m) as bs
263 let
264 k' = theseTable fst fst (const fst) tkab
265 tab = bimap snd snd tkab
266 pure (k', f tab)
269-- | If 'zip' makes an @INNER JOIN@, then 'leftAlign' makes a @LEFT JOIN@.
270-- This means it will return at least one row for every row in the left
271-- 'Tabulation', even if there is no corresponding row in the right (hence the
272-- 'Rel8.MaybeTable').
273--
274-- Analagous to
275-- [@rpadZip@](https://hackage.haskell.org/package/semialign/docs/Data-Semialign.html#v:rpadZip).
276leftAlign :: EqTable k
277 => Tabulation k a -> Tabulation k b -> Tabulation k (a, MaybeTable b)
278leftAlign = leftAlignWith (,)
281-- | See 'zipWith' and 'leftAlign'.
282--
283-- Analagous to
284-- [@rpadZipWith@](https://hackage.haskell.org/package/semialign/docs/Data-Semialign.html#v:rpadZipWith).
285leftAlignWith :: EqTable k
286 => (a -> MaybeTable b -> c)
287 -> Tabulation k a -> Tabulation k b -> Tabulation k c
288leftAlignWith f left right = liftA2 f left (optionalTabulation right)
291-- | Analagous to
292-- [@zip@](https://hackage.haskell.org/package/semialign/docs/Data-Semialign.html#v:zip).
293--
294-- There are multiple correct ways of understanding what this does.
295--
296-- You can think of it as @'Data.Map.Strict.intersectionWith'
297-- ('Control.Applicative.liftA2' (,))@. That is, @intersect@ the two
298-- `Tabulation`s by matching their keys together (with 'Rel8.==:'), and combine
299-- their values (remembering that 'Tabulation' is a 'MultiMap' so that the
300-- values are keys) by getting their cartesian product.
301--
302-- You can think of it as performing a cross product of the underlying 'Query's
303-- of the given 'Tabulation's and filtering the results for 'match'ing keys.
304--
305-- You can think of it as a natural join in SQL terms.
306--
307-- The size of the resulting 'Tabulation' will be \(\sum_{k} min(n_k, m_k) \)
308-- in terms of the number of keys, but \(\sum_{k} n_k \times m_k\) in terms of
309-- the number of values.
310zip :: EqTable k
311 => Tabulation k a -> Tabulation k b -> Tabulation k (a, b)
312zip = zipWith (,)
315-- | Analagous to
316-- [@zipWith@](https://hackage.haskell.org/package/semialign/docs/Data-Semialign.html#v:zipWith).
317--
318-- See 'zip'.
319zipWith :: EqTable k
320 => (a -> b -> c) -> Tabulation k a -> Tabulation k b -> Tabulation k c
321zipWith = liftA2
324-- | 'similarity' returns all the entries in the left 'Tabulation' that have a
325-- corresponding entry in the right 'Tabulation'. This corresponds to a
326-- semijoin in relational algebra.
327--
328-- This differs from @'zipWith' const x y@ when the right 'Tabulation' @y@
329-- contains an entry with multiple rows. For 'similarity', the entries in the
330-- resulting 'Tabulation' will contain the same number of rows as their
331-- respective entries in the left 'Tabulation' @x@. With `zipWith const x y`,
332-- each entry would contain the /product/ of the number of rows of their
333-- respective entries in @x@ and @y@.
334--
335-- See 'Rel8.with'.
336similarity :: EqTable k => Tabulation k a -> Tabulation k b -> Tabulation k a
337similarity kas kbs = do
338 as <- toQuery kas
339 bs <- toQuery kbs
340 fromQuery $ as >>= withBy (\(k, _) (l, _) -> k ==: l) bs
343-- | 'difference' returns all the entries in the left 'Tabulation' that don't
344-- exist in the right 'Tabulation'. This corresponds to an antijoin in
345-- relational algebra.
346--
347-- See 'Rel8.without'.
348difference :: EqTable k => Tabulation k a -> Tabulation k b -> Tabulation k a
349difference kas kbs = do
350 as <- toQuery kas
351 bs <- toQuery kbs
352 fromQuery $ as >>= withoutBy (\(k, _) (l, _) -> k ==: l) bs
355aggregateTabulation :: EqTable k
356 => Tabulation k (Aggregate a) -> Tabulation k a
357aggregateTabulation kas = do
358 as <- toQuery kas
359 fromQuery $ aggregate $ bitraverse1 groupBy id <$> as
362-- | 'orderTabulation' orders the /values/ of a 'Tabulation' (not the keys).
363-- In general this is meaningless, but if used together with 'manyTabulation'
364-- or 'someTabulation', the resulting lists will be ordered according to
365-- ordering given to 'orderTabulation'.
366orderTabulation :: Order a -> Tabulation k a -> Tabulation k a
367orderTabulation ordering (Tabulation as) =
368 Tabulation $ orderBy (snd >$< ordering) . as
371optionalTabulation :: EqTable k
372 => Tabulation k a -> Tabulation k (MaybeTable a)
373optionalTabulation as = Tabulation $ \case
374 Left k -> case as of
375 Tabulation f -> fmap pure <$> f (Left k)
376 Right k -> do
377 ma <- optional $ lookup k as
378 pure (Just k, ma)
381manyTabulation :: (EqTable k, Table Expr a)
382 => Tabulation k a -> Tabulation k (ListTable a)
383manyTabulation =
384 fmap (maybeTable mempty id) .
385 optionalTabulation .
386 aggregateTabulation .
387 fmap listAgg
390someTabulation :: (EqTable k, Table Expr a)
391 => Tabulation k a -> Tabulation k (NonEmptyTable a)
392someTabulation = aggregateTabulation . fmap nonEmptyAgg
395toQuery :: Tabulation k a -> Tabulation k (Query (k, a))
396toQuery (Tabulation as) = Tabulation $ \k ->
397 pure (Nothing, first (fromMaybe (either id id k)) <$> as k)