on a09f128 help sign in
rel8/src/Rel8/Query/Filter.hs
46 lines 1.2 kB history raw
1module Rel8.Query.Filter
2 ( filter
3 , where_
4 )
5where
7-- base
8import Prelude hiding ( filter )
10-- opaleye
11import qualified Opaleye.Operators as Opaleye
13-- profunctors
14import Data.Profunctor ( lmap )
16-- rel8
17import Rel8.Expr ( Expr )
18import Rel8.Expr.Opaleye ( toColumn, toPrimExpr )
19import Rel8.Query ( Query )
20import Rel8.Query.Opaleye ( fromOpaleye )
23-- | @filter f x@ will be a zero-row query when @f x@ is @False@, and will
24-- return @x@ unchanged when @f x@ is @True@. This is similar to
25-- 'Control.Monad.guard', but as the predicate is separate from the argument,
26-- it is easy to use in a pipeline of 'Query' transformations.
27--
28-- >>> select c $ values [ lit x | x <- [ 1..5 :: Int32 ] ] >>= filter (>. 3)
29-- [4,5]
30filter :: (a -> Expr Bool) -> a -> Query a
31filter f a = a <$ where_ (f a)
34-- | Drop any rows that don't match a predicate. @where_ expr@ is equivalent
35-- to the SQL @WHERE expr@.
36--
37-- >>> :{
38-- select c $ do
39-- x <- values [ lit x | x <- [ 1..5 :: Int32 ] ]
40-- where_ $ x >. lit 2
41-- return x
42-- :}
43-- [3,4,5]
44where_ :: Expr Bool -> Query ()
45where_ condition =
46 fromOpaleye $ lmap (\_ -> toColumn $ toPrimExpr condition) Opaleye.restrict