on db148ff help sign in
rel8/src/Rel8/Query/Exists.hs
68 lines 2.0 kB history raw
1{-# language DataKinds #-}
3module Rel8.Query.Exists
4 ( exists, inQuery
5 , whereExists, with, withBy
6 , whereNotExists, without, withoutBy
7 )
8where
10-- base
11import Prelude hiding ( filter )
13-- opaleye
14import qualified Opaleye.Operators as Opaleye
16-- rel8
17import Rel8.Expr ( Expr )
18import Rel8.Query ( Query )
19import Rel8.Query.Filter ( filter )
20import Rel8.Query.Maybe ( optional )
21import Rel8.Query.Opaleye ( mapOpaleye )
22import Rel8.Table.Eq ( EqTable, (==:) )
23import Rel8.Table.Maybe ( isJustTable )
26-- | Checks if a query returns at least one row.
27exists :: Query a -> Query (Expr Bool)
28exists = fmap isJustTable . optional . whereExists
29-- FIXME: change this when b7aacc07c6392654cae439fc3b997620c3aa7a87 makes it
30-- into a release of Opaleye
33inQuery :: EqTable a => a -> Query a -> Query (Expr Bool)
34inQuery a = exists . (>>= filter (a ==:))
37-- | Produce the empty query if the given query returns no rows. @whereExists@
38-- is equivalent to @WHERE EXISTS@ in SQL.
39whereExists :: Query a -> Query ()
40whereExists = mapOpaleye Opaleye.restrictExists
43-- | Produce the empty query if the given query returns rows. @whereNotExists@
44-- is equivalent to @WHERE NOT EXISTS@ in SQL.
45whereNotExists :: Query a -> Query ()
46whereNotExists = mapOpaleye Opaleye.restrictNotExists
49-- | @with@ is similar to 'filter', but allows the predicate to be a full query.
50--
51-- @with f a = a <$ whereExists (f a)@, but this form matches 'filter'.
52with :: (a -> Query b) -> a -> Query a
53with f a = a <$ whereExists (f a)
56-- | Like @with@, but with a custom membership test.
57withBy :: (a -> b -> Expr Bool) -> Query b -> a -> Query a
58withBy predicate bs = with $ \a -> bs >>= filter (predicate a)
61-- | Filter rows where @a -> Query b@ yields no rows.
62without :: (a -> Query b) -> a -> Query a
63without f a = a <$ whereNotExists (f a)
66-- | Like @without@, but with a custom membership test.
67withoutBy :: (a -> b -> Expr Bool) -> Query b -> a -> Query a
68withoutBy predicate bs = without $ \a -> bs >>= filter (predicate a)