1{-# language DeriveFunctor #-}
2{-# language DerivingStrategies #-}
3{-# language FlexibleContexts #-}
4{-# language LambdaCase #-}
5{-# language TupleSections #-}
6{-# language UndecidableInstances #-}
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 )
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
61 , AlternativeTable, emptyTable
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 )
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.
81-- \"Identity\" 'Tabulation's are created using 'tabulate'. 'Tabulation's can
82-- be composed with 'Query's with 'prebind' or 'postbind' to form new
84newtype Tabulation k a = Tabulation (Either k k -> Query (Maybe k, a))
85 deriving stock Functor
88instance EqTable k => Apply (Tabulation k) where
92instance EqTable k => Applicative (Tabulation k) where
93 pure = liftQuery . pure
97instance EqTable k => Bind (Tabulation k) where
101instance EqTable k => Monad (Tabulation k) where
102 Tabulation as >>= f = Tabulation $ \i -> do
105 Nothing -> case f a of
106 Tabulation bs -> bs i
107 Just k -> case f a of
109 (mk', b) <- bs (Right k)
111 Nothing -> pure (mk, b)
117instance EqTable k => AltTable (Tabulation k) where
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)
130 (<>) = alignWith (theseTable id id (<>))
133instance (EqTable k, Table Expr a, Semigroup a) => Monoid (Tabulation k a)
138-- | This "undoes" 'fromQuery'.
141-- 'runTabulation' . 'fromQuery' = id
142-- 'fromQuery' . 'runTabulation' = id
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)
153 -- Opaleye tries to be too clever optimising "WHERE FALSE" and generates
154 -- invalid SQL, so we use "WHERE NOT TRUE" instead
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:
167-- [Tabulation by primary key]:
169-- projectsById :: Project 'Expr' -> 'Tabulation' ('Expr' ProjectId) (Project 'Expr')
170-- projectsById = 'tabulate' projectId
173-- Note: the nature of primary keys means that each key will be mapped to a
174-- singleton value in this case.
176-- [Tabulation by other unique key]:
178-- projectsByName :: Project 'Expr' -> 'Tabulation' ('Expr' Text) (Project 'Expr')
179-- projectsByName = 'tabulate' projectName
182-- [Tabulation by foreign key (tabulate a child table by parent key)]:
184-- revisionsByProjectId :: Revision 'Expr' -> 'Tabulation' ('Expr' ProjectId) (Revision 'Expr')
185-- revisionsByProjectId = 'tabulate' revisionProjectId
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
218 Tabulation query -> query k
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
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
243-- [@align@](https://hackage.haskell.org/package/semialign/docs/Data-Semialign.html#v:align).
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)
252-- [@alignWith@](https://hackage.haskell.org/package/semialign/docs/Data-Semialign.html#v:alignWith).
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
262 tkab <- alignBy (\(l, _) (m, _) -> l ==: m) as bs
264 k' = theseTable fst fst (const fst) tkab
265 tab = bimap snd snd tkab
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').
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'.
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)
292-- [@zip@](https://hackage.haskell.org/package/semialign/docs/Data-Semialign.html#v:zip).
294-- There are multiple correct ways of understanding what this does.
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.
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.
305-- You can think of it as a natural join in SQL terms.
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.
311 => Tabulation k a -> Tabulation k b -> Tabulation k (a, b)
316-- [@zipWith@](https://hackage.haskell.org/package/semialign/docs/Data-Semialign.html#v:zipWith).
320 => (a -> b -> c) -> Tabulation k a -> Tabulation k b -> Tabulation k c
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.
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@.
336similarity :: EqTable k => Tabulation k a -> Tabulation k b -> Tabulation k a
337similarity kas kbs = do
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.
347-- See 'Rel8.without'.
348difference :: EqTable k => Tabulation k a -> Tabulation k b -> Tabulation k a
349difference kas kbs = do
352 fromQuery $ as >>= withoutBy (\(k, _) (l, _) -> k ==: l) bs
355aggregateTabulation :: EqTable k
356 => Tabulation k (Aggregate a) -> Tabulation k a
357aggregateTabulation kas = do
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
375 Tabulation f -> fmap pure <$> f (Left k)
377 ma <- optional $ lookup k as
381manyTabulation :: (EqTable k, Table Expr a)
382 => Tabulation k a -> Tabulation k (ListTable a)
384 fmap (maybeTable mempty id) .
386 aggregateTabulation .
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)
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