World.hs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. {-# LANGUAGE DeriveGeneric #-}
  2. {-# LANGUAGE OverloadedStrings #-}
  3. module Models.World
  4. ( World(..)
  5. , fetchWorldById
  6. , getRandomWorld
  7. , updateWorldRandom
  8. ) where
  9. import Data.Aeson
  10. import Data.Maybe
  11. import Data.Monoid ((<>))
  12. import qualified Database.PostgreSQL.Simple as PG
  13. import Database.PostgreSQL.Simple.FromRow
  14. import GHC.Generics
  15. import System.Random
  16. data World = World
  17. { _idW :: !Integer
  18. , _randomNumberW :: !Integer
  19. } deriving (Show, Generic)
  20. -- | JSON serialization
  21. instance ToJSON World where
  22. toEncoding w =
  23. pairs ( "id" .= _idW w
  24. <> "randomNumber" .= _randomNumberW w
  25. )
  26. {-# INLINE toEncoding #-}
  27. -- | Transforming a database row into a World datatype.
  28. instance FromRow World where
  29. fromRow = World <$> field <*> field
  30. {-# INLINE fromRow #-}
  31. -- | Get a World by Id, this will return a Just World, or Nothing
  32. -- if the id is not in the database.
  33. fetchWorldById :: Int -> PG.Connection -> IO (Maybe World)
  34. fetchWorldById i c =
  35. listToMaybe <$> PG.query c
  36. "SELECT id, randomNumber FROM World WHERE id = ?"
  37. (PG.Only i)
  38. {-# INLINE fetchWorldById #-}
  39. -- | Get a random World from the database. For the tests
  40. -- the id must be bound between 1-10000
  41. getRandomWorld :: PG.Connection -> IO (Maybe World)
  42. getRandomWorld c = do
  43. i <- randomRIO (1, 10000)
  44. fetchWorldById i c
  45. {-# INLINE getRandomWorld #-}
  46. -- | Update a World with a random number
  47. updateWorldRandom :: World -> PG.Connection -> IO World
  48. updateWorldRandom (World _id _) c = do
  49. i <- randomRIO (1, 10000)
  50. _ <- PG.execute c "UPDATE World SET randomNumber = ? WHERE id = ?" (i, _id)
  51. return $ World _id i
  52. {-# INLINE updateWorldRandom #-}