on 9216dbd help sign in
rel8/src/Rel8/Expr/Bool.hs
84 lines 2.1 kB history raw
1module Rel8.Expr.Bool
2 ( false, true
3 , (&&.), (||.), not_
4 , and_, or_
5 , boolExpr
6 , caseExpr
7 , coalesce
8 )
9where
11-- base
12import Data.Foldable ( foldl' )
13import Prelude hiding ( null )
15-- opaleye
16import qualified Opaleye.Internal.HaskellDB.PrimQuery as Opaleye
18-- rel8
19import {-# SOURCE #-} Rel8.Expr ( Expr( Expr ) )
20import Rel8.Expr.Opaleye ( mapPrimExpr, zipPrimExprsWith )
21import Rel8.Expr.Serialize ( litExpr )
24-- | The SQL @false@ literal.
25false :: Expr Bool
26false = litExpr False
29-- | The SQL @true@ literal.
30true :: Expr Bool
31true = litExpr True
34-- | The SQL @AND@ operator.
35(&&.) :: Expr Bool -> Expr Bool -> Expr Bool
36(&&.) = zipPrimExprsWith (Opaleye.BinExpr Opaleye.OpAnd)
37infixr 3 &&.
40-- | The SQL @OR@ operator.
41(||.) :: Expr Bool -> Expr Bool -> Expr Bool
42(||.) = zipPrimExprsWith (Opaleye.BinExpr Opaleye.OpOr)
43infixr 2 ||.
46-- | The SQL @NOT@ operator.
47not_ :: Expr Bool -> Expr Bool
48not_ = mapPrimExpr (Opaleye.UnExpr Opaleye.OpNot)
51-- | Fold @AND@ over a collection of expressions.
52and_ :: Foldable f => f (Expr Bool) -> Expr Bool
53and_ = foldl' (&&.) true
56-- | Fold @OR@ over a collection of expressions.
57or_ :: Foldable f => f (Expr Bool) -> Expr Bool
58or_ = foldl' (||.) false
61-- | Eliminate a boolean-valued expression.
62--
63-- Corresponds to 'Data.Bool.bool'.
64boolExpr :: Expr a -> Expr a -> Expr Bool -> Expr a
65boolExpr ifFalse ifTrue condition = caseExpr [(condition, ifTrue)] ifFalse
68-- | A multi-way if/then/else statement. The first argument to @caseExpr@ is a
69-- list of alternatives. The first alternative that is of the form @(true, x)@
70-- will be returned. If no such alternative is found, a fallback expression is
71-- returned.
72--
73-- Corresponds to a @CASE@ expression in SQL.
74caseExpr :: [(Expr Bool, Expr a)] -> Expr a -> Expr a
75caseExpr branches (Expr fallback) =
76 Expr $ Opaleye.CaseExpr (map go branches) fallback
77 where
78 go (Expr condition, Expr value) = (condition, value)
81coalesce :: Expr (Maybe Bool) -> Expr Bool
82coalesce (Expr a) = Expr a &&. Expr (Opaleye.FunExpr "COALESCE" [a, untrue])
83 where
84 untrue = Opaleye.ConstExpr (Opaleye.BoolLit False)