on 134ddcf help sign in
rel8/src/Rel8/Query/Exists.hs
70 lines 1.8 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.
27--
28-- >>> :{
29-- mapM_ print =<< select c do
30-- author <- each authorSchema
31-- hasProjects <- exists do
32-- project <- each projectSchema
33-- where_ $ authorId author ==. projectAuthorId project
34-- return (authorName author, hasProjects)
35-- :}
36-- ("Ollie",True)
37-- ("Bryan O'Sullivan",True)
38-- ("Emily Pillmore",False)
39exists :: Query a -> Query (Expr Bool)
40exists = fmap isJustTable . optional . whereExists
41-- FIXME: change this when b7aacc07c6392654cae439fc3b997620c3aa7a87 makes it
42-- into a release of Opaleye
45inQuery :: EqTable a => a -> Query a -> Query (Expr Bool)
46inQuery a = exists . (>>= filter (a ==:))
49whereExists :: Query a -> Query ()
50whereExists = mapOpaleye Opaleye.restrictExists
53whereNotExists :: Query a -> Query ()
54whereNotExists = mapOpaleye Opaleye.restrictNotExists
57with :: (a -> Query b) -> a -> Query a
58with f a = a <$ whereExists (f a)
61withBy :: (a -> b -> Expr Bool) -> Query b -> a -> Query a
62withBy predicate bs = with $ \a -> bs >>= filter (predicate a)
65without :: (a -> Query b) -> a -> Query a
66without f a = a <$ whereNotExists (f a)
69withoutBy :: (a -> b -> Expr Bool) -> Query b -> a -> Query a
70withoutBy predicate bs = without $ \a -> bs >>= filter (predicate a)