on 28aaa76 help sign in
rel8/src/Rel8/Expr/Function.hs
94 lines 2.6 kB history raw
1{-# language FlexibleContexts #-}
2{-# language FlexibleInstances #-}
3{-# language MultiParamTypeClasses #-}
4{-# language StandaloneKindSignatures #-}
5{-# language TypeFamilies #-}
6{-# language UndecidableInstances #-}
8module Rel8.Expr.Function
9 ( Function, function
10 , nullaryFunction
11 , binaryOperator
12 )
13where
15-- base
16import Data.Kind ( Constraint, Type )
17import Prelude
19-- opaleye
20import qualified Opaleye.Internal.HaskellDB.PrimQuery as Opaleye
22-- rel8
23import Rel8.Expr ( Expr( Expr ) )
24import Rel8.Expr.Opaleye
25 ( castExpr
26 , fromPrimExpr, toPrimExpr, zipPrimExprsWith
27 )
28import Rel8.Schema.Nullability ( Sql )
29import Rel8.Type ( DBType )
32-- | This type class exists to allow 'function' to have arbitrary arity. It's
33-- mostly an implementation detail, and typical uses of 'Function' shouldn't
34-- need this to be specified.
35type Function :: Type -> Type -> Constraint
36class Function arg res where
37 applyArgument :: ([Opaleye.PrimExpr] -> Opaleye.PrimExpr) -> arg -> res
40instance (arg ~ Expr a, Sql DBType b) => Function arg (Expr b) where
41 applyArgument f a = castExpr $ fromPrimExpr $ f [toPrimExpr a]
44instance (arg ~ Expr a, Function args res) => Function arg (args -> res) where
45 applyArgument f a = applyArgument (f . (toPrimExpr a :))
48-- | Construct an n-ary function that produces an 'Expr' that when called runs
49-- a SQL function.
50--
51-- For example, here's how we can wrap PostgreSQL's @factorial@ function:
52--
53-- >>> :{
54-- factorial :: Expr Int64 -> Expr Data.Scientific.Scientific
55-- factorial = function "factorial"
56-- :}
57--
58-- >>> select c $ pure $ factorial 5
59-- [120.0]
60--
61-- The same approach works for any number of arguments:
62--
63-- >>> :{
64-- power :: Expr Float -> Expr Float -> Expr Double
65-- power = function "power"
66-- :}
67--
68-- >>> select c $ pure $ power 9 3
69-- [729.0]
70function :: Function args result => String -> args -> result
71function = applyArgument . Opaleye.FunExpr
74-- | Construct a function call for functions with no arguments.
75--
76-- For example, we can call the database function @pi()@ by using
77-- @nullaryFunction@:
78--
79-- >>> :{
80-- sqlPi :: Expr Double
81-- sqlPi = nullaryFunction "pi"
82-- :}
83--
84-- >>> select c $ pure $ sqlPi
85-- [3.141592653589793]
86nullaryFunction :: Sql DBType a => String -> Expr a
87nullaryFunction name = castExpr $ Expr (Opaleye.FunExpr name [])
90-- | Construct an expression by applying an infix binary operator to two
91-- operands.
92binaryOperator :: Sql DBType c => String -> Expr a -> Expr b -> Expr c
93binaryOperator operator a b =
94 castExpr $ zipPrimExprsWith (Opaleye.BinExpr (Opaleye.OpOther operator)) a b