Skip to content

Instantly share code, notes, and snippets.

@5outh
Created February 11, 2017 14:07
Show Gist options
  • Save 5outh/5b53643979fb510ded470f8c0bb449e3 to your computer and use it in GitHub Desktop.
Save 5outh/5b53643979fb510ded470f8c0bb449e3 to your computer and use it in GitHub Desktop.
mysql-simple example
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE BangPatterns #-}
module Main where
import Control.Monad.State
import Control.Monad.Reader
import Data.Text
import Database.MySQL.Simple
import Database.MySQL.Simple.QueryParams
import Database.MySQL.Simple.QueryResults
import Database.MySQL.Simple.Param
import Database.MySQL.Simple.Result
import Data.Maybe (fromJust)
data BoardGame = BoardGame
{ name :: Text
, designer :: Text
, year :: Maybe Int
} deriving (Show, Eq)
instance QueryParams BoardGame where
renderParams BoardGame{..} = [render name, render designer, render year]
instance QueryResults BoardGame where
convertResults [fa,fb,fc] [va,vb,vc] = BoardGame a b c
where !a = convert fa va
!b = convert fb vb
!c = convert fc vc
convertResults fs vs = convertError fs vs 3
createGame :: BoardGame -> ReaderT Connection IO (Int, BoardGame)
createGame game = ask >>= \conn -> do
liftIO $ execute
conn
"INSERT INTO board_games (name, designer, year) VALUES (?,?,?)"
game
[Only boardGameId] <- liftIO $ query_ conn "SELECT LAST_INSERT_ID()"
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
connectInfo :: ConnectInfo
connectInfo = defaultConnectInfo
{ connectDatabase = "board_games"
}
main :: IO ()
main = do
conn <- connect connectInfo
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