Skip to content

Instantly share code, notes, and snippets.

@wavewave
Created February 16, 2012 07:13
Show Gist options
  • Select an option

  • Save wavewave/1842888 to your computer and use it in GitHub Desktop.

Select an option

Save wavewave/1842888 to your computer and use it in GitHub Desktop.
using haskelldb with chrisdone's template haskell lib
module Main where
import qualified Model.BookField as F
import qualified Model.BookTable as T
import Database.HaskellDB
import Database.HaskellDB.HDBRec
import Database.HaskellDB.Extra
import Database.HaskellDB.HDBC
import Database.HaskellDB.Sql.PostgreSQL
import Database.HaskellDB.PostgreSQL
import Database.HDBC.PostgreSQL (connectPostgreSQL)
import Data.Pagination
import Data.Default
import System.IO
import Control.Exception
getPassword :: IO String
getPassword = do
putStr "Password: "
hFlush stdout
pass <- withEcho False getLine
putChar '\n'
return pass
withEcho :: Bool -> IO a -> IO a
withEcho echo action = do
old <- hGetEcho stdin
bracket_ (hSetEcho stdin echo) (hSetEcho stdin old) action
simpleSelection = do
table T.books
simpleInsert conn = do
insert conn
T.books
( F.id << val 1
# F.title << val "hello world")
withDB opts = hdbcConnect generator (connectPostgreSQL conninfo)
where conninfo = unwords [ k ++ "=" ++ v | (k,v) <- opts]
opts username password dbname =
[("host","localhost")
,("user",username)
,("password",password)
,("dbname",dbname)]
main = do
username <- putStr "username : " >> hFlush stdout >> getLine
password <- getPassword
dbname <- putStr "dbname : " >> hFlush stdout >> getLine
r <- withDB (opts username password dbname)
(\db-> -- simpleInsert db)
query db simpleSelection)
print $ r
{-# LANGUAGE TemplateHaskell #-}
-- | All database fields.
module Model.BookField where
import Database.HaskellDB.PostgreSQL
import Database.HaskellDB.TH
field "Id" "id" "id" [t|Int|]
field "Title" "title" "title" [t|String|]
{-# LANGUAGE TemplateHaskell #-}
-- | Database tables and entities.
module Model.BookTable where
import Model.BookField as Field
import Database.HaskellDB.TH
import Prelude ()
-- | Content table.
table "books" "books"
['id
,'title
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment