-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathUtils.hs
217 lines (182 loc) · 7.05 KB
/
Utils.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
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
module Database.Groundhog.Utils
( Entity(..)
, Entity'
-- * Querying
, selectEntity
, selectProducer
-- * Keys
, getKey
, mkKey
, keyToInt
, keyToIntegral
, intToKey
, integralToKey
-- * Serialization
, SC(..)
, getSC
, Sh(..)
, getSh
) where
-------------------------------------------------------------------------------
import Control.Lens
import Control.Monad.Base
import Control.Monad.IO.Class
import Control.Monad.Loops (whileJust_)
import Control.Monad.Trans.Class
import Control.Monad.Trans.Resource
import qualified Data.Acquire as Acquire
import Data.Aeson hiding (Key(..))
import Data.ByteString.Char8 (ByteString)
import Data.Conduit
import Data.Default
import Data.SafeCopy
import Data.Serialize
import Data.Typeable
import Database.Groundhog as GH
import Database.Groundhog.Core as GH
import Database.Groundhog.Generic as GH
import GHC.Generics
-------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- | Data type holding a key and its associated value. This is used for
-- convenience functions like selectEntity that abstract the common pattern of
-- getting a row and its auto-incremented key.
data Entity k v = Entity
{ entityKey :: k
, entityVal :: v
} deriving (Show, Eq, Ord, Generic, Typeable)
-- | The Common case of an entity with a matching key. You almost
-- never need a key that doesn't track the 'entityVal' type.
type Entity' v = Entity (DefaultKey v) v
-------------------------------------------------------------------------------
-- | Convenience wrapper aronud groundhog's 'select' function that also
-- returns keys with each result row.
selectEntity
:: ( EntityConstr v c
, Projection' p conn (RestrictionHolder v c) a
, HasSelectOptions opts conn (RestrictionHolder v c)
, PersistBackend m
, Conn m ~ conn
, Projection p v
)
=> p
-> opts
-> m [Entity (AutoKey v) v]
selectEntity constructor cond = do
res <- project (AutoKeyField, constructor) cond
return $ map (uncurry Entity) res
-------------------------------------------------------------------------------
-- | Takes groundhog's streaming-framework-agnostic 'selectStream' to
-- a conduit producer.
selectProducer
:: forall v c conn m ctor opts b i.
( EntityConstr v c
, HasSelectOptions opts conn (RestrictionHolder v c)
, PersistBackend m
, Conn m ~ conn
, MonadBase IO m
, Projection ctor b
, ProjectionDb ctor conn
, ProjectionRestriction ctor (RestrictionHolder v c)
, MonadThrow m
)
=> ctor
-> opts
-> ConduitM i (Entity (AutoKey v) b) (ResourceT m) ()
selectProducer ctor opts = do
rowStream <- fmap (fmap (fmap (uncurry Entity))) <$>
lift (lift (projectStream (AutoKeyField, ctor) opts))
rowStreamProducer rowStream
-------------------------------------------------------------------------------
rowStreamProducer
:: ( MonadIO m
, MonadThrow m
, MonadBase IO m
)
=> RowStream a
-> ConduitM i a (ResourceT m) ()
rowStreamProducer rowStream = do
(releaseKey, rowIterator) <- Acquire.allocateAcquire rowStream
whileJust_ (liftIO rowIterator) yield
release releaseKey
-------------------------------------------------------------------------------
-- | Pull the Int out of a db AutoKey.
getKey :: (SinglePersistField a, PersistBackend m) => a -> m Int
getKey k = toSinglePersistValue k >>= fromSinglePersistValue
-------------------------------------------------------------------------------
mkKey :: (PersistBackend m, SinglePersistField a, SinglePersistField b) => a -> m b
mkKey k = toSinglePersistValue k >>= fromSinglePersistValue
-------------------------------------------------------------------------------
keyToInt
:: (PrimitivePersistField (Key a b))
=> Key a b
-> Int
keyToInt = keyToIntegral
-------------------------------------------------------------------------------
-- | Convert 'Key' to any integral type.
keyToIntegral
:: (PrimitivePersistField i, PrimitivePersistField (Key a b))
=> Key a b
-> i
keyToIntegral =
fromPrimitivePersistValue . toPrimitivePersistValue
-------------------------------------------------------------------------------
-- | Type specialized input for type inference convenience.
intToKey
:: (PrimitivePersistField (Key a b))
=> Int
-> Key a b
intToKey = integralToKey
-------------------------------------------------------------------------------
-- | Convert any integral type to 'Key'
integralToKey
:: (PrimitivePersistField i, PrimitivePersistField (Key a b))
=> i
-> Key a b
integralToKey =
fromPrimitivePersistValue . toPrimitivePersistValue
-- | SafeCopy PrimitivePersistField wrapper. Anything you stuff in
-- here will be persisted in database as a SafeCopy blob.
newtype SC a = SC { _getSC :: a }
deriving (Eq,Show,Read,Ord,Generic,Typeable,ToJSON,FromJSON)
makeLenses ''SC
makeWrapped ''SC
instance NeverNull (SC a)
instance SafeCopy a => PersistField (SC a) where
persistName _ = "SC" ++ delim : delim : persistName (undefined :: ByteString)
toPersistValues = primToPersistValue
fromPersistValues = primFromPersistValue
dbType _ _ = DbTypePrimitive DbBlob False Nothing Nothing
instance SafeCopy a => PrimitivePersistField (SC a) where
toPrimitivePersistValue (SC a) = toPrimitivePersistValue $ runPut $ safePut a
fromPrimitivePersistValue x =
either (error "SafeCopy failed in SC wrapper.") SC $
runGet safeGet (fromPrimitivePersistValue x)
-- | Show PrimitivePersistField wrapper. Wrap your data into this and
-- it will be marshalled to groundhog via its read/show instances.
newtype Sh a = Sh { _getSh :: a }
deriving (Eq,Show,Read,Ord,Generic,Typeable,Default,ToJSON,FromJSON)
makeLenses ''Sh
makeWrapped ''Sh
instance NeverNull (Sh a)
instance (Show a, Read a) => PersistField (Sh a) where
persistName _ = "Sh" ++ delim : delim : persistName (undefined :: ByteString)
toPersistValues = primToPersistValue
fromPersistValues = primFromPersistValue
dbType _ _ = DbTypePrimitive DbString False Nothing Nothing
instance (Show a, Read a) => PrimitivePersistField (Sh a) where
toPrimitivePersistValue (Sh a) = toPrimitivePersistValue $ show a
fromPrimitivePersistValue x = Sh $ read (fromPrimitivePersistValue x)