Skip to content

Instantly share code, notes, and snippets.

@ToJans
Last active Oct 21, 2015
Embed
What would you like to do?
How do I get this into a ServerT ?
{-# LANGUAGE OverloadedStrings #-}
module Lib.DB(query_,query,execute_,execute,lastInsertRowId
,find,DB.FromRow,DB.fromRow,DB.field,ResourceT,runResourceT)
where
import Control.Monad (liftM)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Reader (ReaderT (..), ask, runReader)
import Control.Monad.Trans.Class (lift)
import Data.Int (Int64)
import qualified Database.SQLite.Simple as DB
import Database.SQLite.Simple.FromField (FromField)
type ResourceT a = ReaderT DB.Connection IO a
runResourceT :: String -> ResourceT a -> IO a
runResourceT connstr f = do
conn <- DB.open connstr
let r = runReaderT f conn
DB.close conn
r
query :: (DB.ToRow a, DB.FromRow b) => DB.Query -> a -> ResourceT [b]
query qry pars = do
conn <- ask
liftIO $ DB.query conn qry pars
query_ :: DB.FromRow a => DB.Query -> ResourceT [a]
query_ qry = do
conn <- ask
liftIO $ DB.query_ conn qry
execute :: (DB.ToRow a) => DB.Query -> a -> ResourceT ()
execute qry pars = do
conn <- ask
liftIO $ DB.execute conn qry pars
execute_ :: DB.Query -> ResourceT ()
execute_ qry = do
conn <- ask
liftIO $ DB.execute_ conn qry
lastInsertRowId :: ResourceT Int64
lastInsertRowId = do
conn <- ask
liftIO $ DB.lastInsertRowId conn
find:: (DB.ToRow a, DB.FromRow b) => DB.Query -> a -> ResourceT (Maybe b)
find sql pars = do
rows <- query sql pars
case rows of
[] -> return Nothing
[x] -> return (Just x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment