forked from yesodweb/persistent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInit.hs
More file actions
314 lines (265 loc) · 8.78 KB
/
Init.hs
File metadata and controls
314 lines (265 loc) · 8.78 KB
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
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TemplateHaskell #-}
module Init (
(@/=), (@==), (==@)
, assertNotEqual
, assertNotEmpty
, assertEmpty
, isTravis
, BackendMonad
, runConn
, MonadIO
, persistSettings
, MkPersistSettings (..)
#ifdef WITH_NOSQL
, dbName
, db'
, setup
, mkPersistSettings
, Action
, Context
#else
, db
, sqlite_database
#endif
, BackendKey(..)
, generateKey
-- re-exports
, module Database.Persist
, module Test.Hspec
, module Test.HUnit
, liftIO
, mkPersist, mkMigrate, share, sqlSettings, persistLowerCase, persistUpperCase
, Int32, Int64
, Text
, module Control.Monad.Trans.Reader
, module Control.Monad
#ifndef WITH_NOSQL
, module Database.Persist.Sql
#endif
) where
-- re-exports
import Control.Monad.Trans.Reader
import Test.Hspec
import Database.Persist.TH (mkPersist, mkMigrate, share, sqlSettings, persistLowerCase, persistUpperCase, MkPersistSettings(..))
-- testing
import Test.HUnit ((@?=),(@=?), Assertion, assertFailure, assertBool)
import Test.QuickCheck
import Database.Persist
import Database.Persist.TH ()
import Data.Text (Text, unpack)
import System.Environment (getEnvironment)
import qualified Data.ByteString as BS
#ifdef WITH_NOSQL
import Language.Haskell.TH.Syntax (Type(..))
import Database.Persist.TH (mkPersistSettings)
import Control.Monad (void, replicateM, liftM)
# ifdef WITH_MONGODB
import qualified Database.MongoDB as MongoDB
import Database.Persist.MongoDB (Action, withMongoPool, runMongoDBPool, defaultMongoConf, applyDockerEnv, BackendKey(..))
# endif
# ifdef WITH_ZOOKEEPER
import qualified Database.Zookeeper as Z
import Database.Persist.Zookeeper (Action, withZookeeperPool, runZookeeperPool, ZookeeperConf(..), defaultZookeeperConf, BackendKey(..), deleteRecursive)
import Data.IORef (newIORef, IORef, writeIORef, readIORef)
import System.IO.Unsafe (unsafePerformIO)
import qualified Data.Text as T
# endif
#else
import Control.Monad (liftM)
import Database.Persist.Sql
import Control.Monad.Trans.Resource (ResourceT, runResourceT)
import Control.Monad.Logger
import System.Log.FastLogger (fromLogStr)
# ifdef WITH_POSTGRESQL
import Control.Applicative ((<$>))
import Database.Persist.Postgresql
import Data.Maybe (fromMaybe)
import Data.Monoid ((<>))
# else
# ifndef WITH_MYSQL
import Database.Persist.Sqlite
# endif
# endif
# ifdef WITH_MYSQL
import Database.Persist.MySQL
# endif
import Data.IORef (newIORef, IORef, writeIORef, readIORef)
import System.IO.Unsafe (unsafePerformIO)
#endif
import Control.Monad (unless, (>=>))
import Control.Monad.Trans.Control (MonadBaseControl)
-- Data types
import Data.Int (Int32, Int64)
import Control.Monad.IO.Class
#ifdef WITH_MONGODB
setup :: Action IO ()
setup = setupMongo
type Context = MongoDB.MongoContext
#endif
#ifdef WITH_ZOOKEEPER
setup :: Action IO ()
setup = setupZookeeper
type Context = Z.Zookeeper
#endif
(@/=), (@==), (==@) :: (Eq a, Show a, MonadIO m) => a -> a -> m ()
infix 1 @/= --, /=@
actual @/= expected = liftIO $ assertNotEqual "" expected actual
infix 1 @==, ==@
expected @== actual = liftIO $ expected @?= actual
expected ==@ actual = liftIO $ expected @=? actual
{-
expected /=@ actual = liftIO $ assertNotEqual "" expected actual
-}
assertNotEqual :: (Eq a, Show a) => String -> a -> a -> Assertion
assertNotEqual preface expected actual =
unless (actual /= expected) (assertFailure msg)
where msg = (if null preface then "" else preface ++ "\n") ++
"expected: " ++ show expected ++ "\n to not equal: " ++ show actual
assertEmpty :: (Monad m, MonadIO m) => [a] -> m ()
assertEmpty xs = liftIO $ assertBool "" (null xs)
assertNotEmpty :: (Monad m, MonadIO m) => [a] -> m ()
assertNotEmpty xs = liftIO $ assertBool "" (not (null xs))
isTravis :: IO Bool
isTravis = do
env <- liftIO getEnvironment
return $ case lookup "TRAVIS" env of
Just "true" -> True
_ -> False
#ifdef WITH_POSTGRESQL
dockerPg :: IO (Maybe BS.ByteString)
dockerPg = do
env <- liftIO getEnvironment
return $ case lookup "POSTGRES_NAME" env of
Just _name -> Just "postgres" -- /persistent/postgres
_ -> Nothing
#endif
#ifdef WITH_NOSQL
persistSettings :: MkPersistSettings
persistSettings = (mkPersistSettings $ ConT ''Context) { mpsGeneric = True }
dbName :: Text
dbName = "persistent"
type BackendMonad = Context
#ifdef WITH_MONGODB
runConn :: (MonadIO m, MonadBaseControl IO m) => Action m backend -> m ()
runConn f = do
conf <- liftIO $ applyDockerEnv $ defaultMongoConf dbName -- { mgRsPrimary = Just "replicaset" }
void $ withMongoPool conf $ runMongoDBPool MongoDB.master f
setupMongo :: Action IO ()
setupMongo = void $ MongoDB.dropDatabase dbName
#endif
#ifdef WITH_ZOOKEEPER
runConn :: (MonadIO m, MonadBaseControl IO m) => Action m backend -> m ()
runConn f = do
let conf = defaultZookeeperConf {zCoord = "localhost:2181/" ++ T.unpack dbName}
void $ withZookeeperPool conf $ runZookeeperPool f
setupZookeeper :: Action IO ()
setupZookeeper = do
liftIO $ Z.setDebugLevel Z.ZLogError
deleteRecursive "/"
#endif
db' :: Action IO () -> Action IO () -> Assertion
db' actions cleanDB = do
r <- runConn (actions >> cleanDB)
return r
instance Arbitrary PersistValue where
arbitrary = PersistObjectId `fmap` BS.pack `fmap` replicateM 12 arbitrary
#else
persistSettings :: MkPersistSettings
persistSettings = sqlSettings { mpsGeneric = True }
type BackendMonad = SqlBackend
sqlite_database :: Text
sqlite_database = "test/testdb.sqlite3"
-- sqlite_database = ":memory:"
runConn :: (MonadIO m, MonadBaseControl IO m) => SqlPersistT (LoggingT m) t -> m ()
#ifdef DEBUG
runConn f = flip runLoggingT (\_ _ _ s -> print $ fromLogStr s) $ do
#else
runConn f = flip runLoggingT (\_ _ _ s -> return ()) $ do
#endif
# ifdef WITH_POSTGRESQL
travis <- liftIO isTravis
_ <- if travis
then withPostgresqlPool "host=localhost port=5432 user=postgres dbname=persistent" 1 $ runSqlPool f
else do
host <- fromMaybe "localhost" <$> liftIO dockerPg
withPostgresqlPool ("host=" <> host <> " port=5432 user=postgres dbname=test") 1 $ runSqlPool f
# else
# ifdef WITH_MYSQL
travis <- liftIO isTravis
_ <- if not travis
then withMySQLPool defaultConnectInfo
{ connectHost = "localhost"
, connectUser = "test"
, connectPassword = "test"
, connectDatabase = "test"
} 1 $ runSqlPool f
else withMySQLPool defaultConnectInfo
{ connectHost = "localhost"
, connectUser = "travis"
, connectPassword = ""
, connectDatabase = "persistent"
} 1 $ runSqlPool f
# else
_<-withSqlitePool sqlite_database 1 $ runSqlPool f
# endif
# endif
return ()
db :: SqlPersistT (LoggingT (ResourceT IO)) () -> Assertion
db actions = do
runResourceT $ runConn $ actions >> transactionUndo
#if !MIN_VERSION_random(1,0,1)
instance Random Int32 where
random g =
let ((i::Int), g') = random g in
(fromInteger $ toInteger i, g')
randomR (lo, hi) g =
let ((i::Int), g') = randomR (fromInteger $ toInteger lo, fromInteger $ toInteger hi) g in
(fromInteger $ toInteger i, g')
instance Random Int64 where
random g =
let ((i0::Int32), g0) = random g
((i1::Int32), g1) = random g0 in
(fromInteger (toInteger i0) + fromInteger (toInteger i1) * 2 ^ (32::Int), g1)
randomR (lo, hi) g = -- TODO : generate on the whole range, and not only on a part of it
let ((i::Int), g') = randomR (fromInteger $ toInteger lo, fromInteger $ toInteger hi) g in
(fromInteger $ toInteger i, g')
#endif
instance Arbitrary PersistValue where
arbitrary = PersistInt64 `fmap` choose (0, maxBound)
#endif
instance PersistStore backend => Arbitrary (BackendKey backend) where
arbitrary = (errorLeft . fromPersistValue) `fmap` arbitrary
where
errorLeft x = case x of
Left e -> error $ unpack e
Right r -> r
#ifdef WITH_NOSQL
#ifdef WITH_MONGODB
generateKey :: IO (BackendKey Context)
generateKey = MongoKey `liftM` MongoDB.genObjectId
#endif
#ifdef WITH_ZOOKEEPER
keyCounter :: IORef Int64
keyCounter = unsafePerformIO $ newIORef 1
{-# NOINLINE keyCounter #-}
generateKey :: IO (BackendKey Context)
generateKey = do
i <- readIORef keyCounter
writeIORef keyCounter (i + 1)
return $ ZooKey $ T.pack $ show i
#endif
#else
keyCounter :: IORef Int64
keyCounter = unsafePerformIO $ newIORef 1
{-# NOINLINE keyCounter #-}
generateKey :: IO (BackendKey SqlBackend)
generateKey = do
i <- readIORef keyCounter
writeIORef keyCounter (i + 1)
return $ SqlBackendKey $ i
#endif