forked from circuithub/rel8
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Rel8.hs
379 lines (310 loc) · 11.5 KB
/
Rel8.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
{-# LANGUAGE Arrows #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
module Rel8
( -- $welcome
-- * Defining Tables
-- $defining
C
, Anon
, HasDefault(..)
, BaseTable(tableName)
, Table
-- * Querying Tables
, O.Query, O.QueryArr
, queryTable
, leftJoin
, leftJoinA
, unionAll
, O.restrictExists, O.restrictNotExists
-- ** Filtering
, where_
, filterQuery
, distinct
-- ** Offset and limit
, O.limit
, O.offset
-- ** Ordering
, asc, desc, orderNulls, O.orderBy, OrderNulls(..)
-- * Aggregation
, aggregate
, AggregateTable
, count, groupBy, DBSum(..), countStar, DBMin(..), DBMax(..), DBAvg(..)
, boolAnd, boolOr, stringAgg, arrayAgg, countDistinct
, countRows, Aggregate
-- * Tables
, MaybeTable, isTableNull
, Col(..)
-- * Expressions
, Expr, coerceExpr, dbShow, case_
-- ** Equality
, DBEq, (==.), in_, ilike
-- ** Ordering
, DBOrd, (>.), (>=.), (<.), (<=.)
-- ** Numeric Operators
, (+), (-), negate, (*)
-- ** Booleans
, (&&.), (||.), not_, Predicate
-- ** Literals
, DBType(..), lit, dbNow
, TypeInfo(..), showableDbType, compositeDBType
-- ** Null
, ToNullable(toNullable) , ($?), isNull, nullable
, liftOpNull, mapNull
-- *** Null-lifted operators
-- $nullLift
, (==?), (<?), (<=?), (>?), (>=?)
, (||?), (&&?), (+?), (*?), (-?)
, (/?)
-- * Running Queries
-- ** @SELECT@
, select
-- ** @INSERT@
, Default(..), Insert
, insert, insert1Returning {- , insertReturning -}
-- ** @UPDATE@
, update {- , updateReturning -}
-- ** @DELETE@
, delete
-- * Interpretations
, QueryResult, SchemaInfo
-- * Re-exported symbols
, Connection, Stream, Of, Generic
-- * Unsafe routines
, unsafeCoerceExpr
, unsafeCastExpr
, unsafeLiteral
, dbFunction
, nullaryFunction
, dbBinOp
) where
import Control.Applicative (liftA2)
import Control.Category ((.), id)
import Control.Lens (view, from)
import Control.Monad.Rel8
import Data.Functor.Rep (mzipWithRep)
import Data.List (foldl')
import Data.Profunctor (lmap)
import Data.Text (Text)
import Data.Time (UTCTime)
import Database.PostgreSQL.Simple (Connection)
import GHC.Generics (Generic)
import qualified Opaleye.Binary as O
import qualified Opaleye.Column as O
import qualified Opaleye.Internal.Aggregate as O
import qualified Opaleye.Internal.Binary as O
import qualified Opaleye.Internal.Column as O
import qualified Opaleye.Internal.Distinct as O
import qualified Opaleye.Internal.HaskellDB.PrimQuery as O
import qualified Opaleye.Internal.Join as O
import qualified Opaleye.Internal.PGTypes as O
import qualified Opaleye.Internal.PackMap as O
import qualified Opaleye.Internal.PrimQuery as PrimQuery
import qualified Opaleye.Internal.QueryArr as O
import qualified Opaleye.Internal.Tag as O
import qualified Opaleye.Internal.Unpackspec as O
import qualified Opaleye.Join as O
import qualified Opaleye.Operators as O
import qualified Opaleye.Order as O
import Prelude hiding (not, (.), id)
import Rel8.Internal
import Streaming (Of, Stream)
infix 4 ==? , <? , <=? , >? , >=?
infixr 2 ||?
infixr 3 &&?
infixl 7 *?
infixl 6 +?, -?
infixr 7 /?
--------------------------------------------------------------------------------
(==?)
:: (DBEq a, ToNullable l (Maybe a), ToNullable r (Maybe a))
=> Expr l -> Expr r -> Expr (Maybe Bool)
a ==? b = liftOpNull (==.) (toNullable a) (toNullable b)
(<?), (<=?), (>?), (>=?)
:: (DBOrd a, ToNullable l (Maybe a), ToNullable r (Maybe a))
=> Expr l -> Expr r -> Expr (Maybe Bool)
a <? b = liftOpNull (<.) (toNullable a) (toNullable b)
a <=? b = liftOpNull (<=.) (toNullable a) (toNullable b)
a >? b = liftOpNull (>.) (toNullable a) (toNullable b)
a >=? b = liftOpNull (>=.) (toNullable a) (toNullable b)
(||?), (&&?)
:: (ToNullable bool1 (Maybe Bool), ToNullable bool2 (Maybe Bool))
=> Expr bool1 -> Expr bool2 -> Expr (Maybe Bool)
a ||? b = liftOpNull (||.) (toNullable a) (toNullable b)
a &&? b = liftOpNull (&&.) (toNullable a) (toNullable b)
(+?), (*?), (-?)
:: (Num (Expr a), ToNullable l (Maybe a), ToNullable r (Maybe a))
=> Expr l -> Expr r -> Expr (Maybe a)
a +? b = liftOpNull (+) (toNullable a) (toNullable b)
a *? b = liftOpNull (*) (toNullable a) (toNullable b)
a -? b = liftOpNull (-) (toNullable a) (toNullable b)
(/?)
:: (Fractional (Expr a), ToNullable l (Maybe a), ToNullable r (Maybe a))
=> Expr l -> Expr r -> Expr (Maybe a)
a /? b = liftOpNull (/) (toNullable a) (toNullable b)
--------------------------------------------------------------------------------
unsafeLiteral :: String -> Expr a
unsafeLiteral = columnToExpr . O.literalColumn . O.OtherLit
--------------------------------------------------------------------------------
-- | Take the @LEFT JOIN@ of two queries.
leftJoin
:: (Table left a, Table right b, Predicate bool)
=> (left -> right -> Expr bool) -- ^ The condition to join upon.
-> O.Query left -- ^ The left table
-> O.Query right -- ^ The right table
-> O.Query (left,MaybeTable right)
leftJoin condition l r =
O.leftJoinExplicit
unpackColumns
unpackColumns
(O.NullMaker (\(tag, t) -> MaybeTable tag t))
l
(liftA2 (,) (pure (lit (Just False))) r)
(\(a, (_, b)) -> exprToColumn (toNullable (condition a b)))
--------------------------------------------------------------------------------
-- | A more convenient form of 'leftJoin' when using arrow notation.
-- @inlineLeftJoinA@ takes the left join of all proceeding queries against a
-- given query. The input to the 'QueryArr' is a predicate function against
-- rows in the to-be-joined query.
--
-- === Example
-- @
-- -- Return all users and comments, including users who haven't made a comment.
-- usersAndComments :: Query (User Expr, MaybeTable (Comment Expr))
-- proc _ -> do
-- u <- queryTable -< ()
-- comment <- inlineLeftJoinA -< \c -> commentUser c ==. userId u
-- returnA (u, c)
-- @
leftJoinA
:: (Table a haskell, Predicate bool)
=> O.Query a -> O.QueryArr (a -> Expr bool) (MaybeTable a)
leftJoinA q =
O.QueryArr $ \(p, left, t) ->
let O.QueryArr rightQueryF = liftA2 (,) (pure (lit (Just False))) q
(right, pqR, t') = rightQueryF ((), PrimQuery.Unit, t)
((tag, renamed), ljPEsB) =
O.run
(O.runUnpackspec unpackColumns (O.extractLeftJoinFields 2 t') right)
in ( MaybeTable tag renamed
, PrimQuery.Join
PrimQuery.LeftJoin
(case toNullable (p renamed) of
Expr a -> a)
[] -- TODO ?
ljPEsB
left
pqR
, O.next t')
-- | Take only distinct rows in a 'O.Query'. This maps to grouping by every
-- column in the table.
distinct :: Table table haskell => O.Query table -> O.Query table
distinct =
O.distinctExplicit
(O.Distinctspec
(O.Aggregator (O.PackMap (\f -> traversePrimExprs (\e -> f (Nothing,e))))))
-- | Restrict a 'O.QueryArr' to only contain rows that satisfy a given predicate.
where_ :: Predicate bool => O.QueryArr (Expr bool) ()
where_ = lmap (exprToColumn . toNullable) O.restrict
-- | Filter a 'O.Query' into a new query where all rows satisfy a given
-- predicate.
filterQuery :: Predicate bool => (a -> Expr bool) -> O.Query a -> O.Query a
filterQuery f q = proc _ -> do
row <- q -< ()
where_ -< f row
id -< row
-- | Corresponds to the @IS NULL@ operator.
isNull :: Expr (Maybe a) -> Expr Bool
isNull = columnToExpr . O.isNull . exprToColumn
-- | Test if an 'Expr' is in a list of 'Expr's. This is performed by folding
-- '==.' over all values and combining them with '||.'.
in_ :: DBEq a => Expr a -> [Expr a] -> Expr Bool
in_ x = foldl' (\b y -> x ==. y ||. b) (lit False)
-- | Corresponds to the @ILIKE@ operator.
ilike :: Expr Text -> Expr Text -> Expr Bool
a `ilike` b =
columnToExpr (O.binOp (O.OpOther "ILIKE") (exprToColumn a) (exprToColumn b))
dbBinOp :: String -> Expr a -> Expr b -> Expr c
dbBinOp op a b =
columnToExpr (O.binOp (O.OpOther op) (exprToColumn a) (exprToColumn b))
-- | Corresponds to the @now()@ function.
dbNow :: Expr UTCTime
dbNow = nullaryFunction "now"
-- | Take the union of all rows in the first query and all rows in the second
-- query. Corresponds to the PostgreSQL @UNION ALL@ operator.
unionAll :: Table table haskell => O.Query table -> O.Query table -> O.Query table
unionAll =
O.unionAllExplicit
(O.Binaryspec
(O.PackMap
(\f (l, r) ->
fmap
(view (from expressions))
(sequenceA
((mzipWithRep
(\prim1 prim2 -> f (prim1, prim2))
(view expressions l)
(view expressions r)))))))
{- $welcome
Welcome to Rel8! Rel8 is an API built on top of the fantastic Opaleye library to
provide an easy and type-safe way to interact with relational databases.
The main objectives of Rel8 are:
* Conciseness: Users using Rel8 should not need to write boiler-plate code. By
using expressive types, we can provide sufficient information for the compiler
to infer code whenever possible.
* Inferrable: Despite using a lot of type level magic, it should never be a
requirement that the user must provide a type signature to allow a program to compile.
* Compatible: Rel8 tries to use the existing Opaleye API as much as possible.
If you're new to Rel8, you're encouraged to check out the documentation over at
<https://rel8.readthedocs.io/en/latest/ Read The Docs>, where a comprehensive
Getting Started guide is provided, along with a comparison with traditional
Opaleye code.
-}
{- $defining
The idiomatic way to define tables in Rel8 is to use a Haskell record. However,
as a table might be used in a query, or in query results, we need to two
different "viwes" on this record. We achieve this by parameterising the record
with a particular interpretation. This is done by providing a type parameter,
and then using the 'C' type family to map this interpretation to a particular
Haskell type.
For example, we might have a record for a Haskell library on Hackage:
@
data Library f = Library
{ libraryName :: C f "name" 'NoDefault Text
, libraryUploadedAt :: C f "uploaded_at" 'NoDefault UTCTime
}
@
To use this type with Rel8, we just need to define a few instances. This is
boiler plate code, and it can be automated with GHC Generics. The final
type definition is:
@
data Library f = Library
{ libraryName :: C f "name" 'NoDefault Text
, libraryUploadedAt :: C f "uploaded_at" 'NoDefault UTCTime
} deriving (Generic)
instance (expr ~ Expr, result ~ QueryResult) => Table (Library expr) (Library result)
instance BaseTable Library where tableName = "hackage_libraryr"
@
(The strange instance declaration may look a bit scary, but will give you /much/
better type inference! This is discussed in a bit more detail
<https://rel8.readthedocs.io/en/latest/concepts.html#even-more-type-inference here>)
-}
{- $nullLift
Null-lifted operators work like their conventional operators, but they also
allow @null@ as either argument. These functions are defined in the PostgreSQL
engine as short-circuiting with a return value of @nulL@ if either argument is
@null@.
You may find these operators convenient when mixing nullable types.
-}