Created
February 9, 2017 01:40
-
-
Save 5outh/31acec58bbd91413d71a0df2638fe899 to your computer and use it in GitHub Desktop.
postgresql-simple
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE RecordWildCards #-} | |
{-# LANGUAGE OverloadedStrings #-} | |
import Control.Monad.State | |
import Control.Monad.Reader | |
import Data.Text | |
import Database.PostgreSQL.Simple | |
import Database.PostgreSQL.Simple.FromRow | |
import Database.PostgreSQL.Simple.ToRow | |
import Data.Maybe (fromJust) | |
data BoardGame = BoardGame | |
{ name :: Text | |
, designer :: Text | |
, year :: Maybe Int | |
} deriving (Show, Eq) | |
instance FromRow BoardGame where | |
fromRow = BoardGame <$> field <*> field <*> field | |
instance ToRow BoardGame where | |
toRow BoardGame{..} = toRow (name, designer, year) | |
createGame :: BoardGame -> ReaderT Connection IO (Int, BoardGame) | |
createGame game = ask >>= \conn -> do | |
[Only boardGameId] <- liftIO $ query | |
conn | |
"INSERT INTO board_games (name, designer, year) VALUES (?,?,?) RETURNING id" | |
game | |
game' <- fromJust <$> readGame boardGameId | |
pure (boardGameId, game') | |
readGame :: Int -> ReaderT Connection IO (Maybe BoardGame) | |
readGame boardGameId = ask >>= \conn -> do | |
games <- liftIO $ query | |
conn | |
"SELECT name, designer, year FROM board_games WHERE id = ?" | |
(Only boardGameId) | |
pure $ case games of | |
[g] -> Just g | |
_ -> Nothing | |
main :: IO () | |
main = do | |
conn <- connectPostgreSQL "host=localhost port=5432 connect_timeout=10" | |
flip runReaderT conn $ do | |
result <- createGame $ BoardGame | |
"Cosmic Encounter" | |
"Bill Eberle" | |
(Just 2008) | |
liftIO $ print result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment