Instantly share code, notes, and snippets.

Embed
What would you like to do?
postgresql-simple
{-# 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