module DB where

import Database.HDBC
import Database.HDBC.PostgreSQL

conn_settings = "host=localhost dbname=ca user=ca"
db_insert statement =
    do conn <- connectPostgreSQL conn_settings
       sth <- prepare conn statement
       handleSqlError $ execute sth []
       commit conn
       return ()

db_select statement =
    do conn <- connectPostgreSQL conn_settings
       r <- quickQuery conn statement []
       return r

db_update statement params = do
    conn <- connectPostgreSQL conn_settings
    sRun conn statement $ map Just params
    commit conn
    return ()

-- returns the first column of the first result row as a String
db_firstvalue :: String -> IO String
db_firstvalue statement = do
    r <- db_select statement
    if (length r == 0)
        then return ""
        else do
            let firstvalue = (fromSql . head . head) r :: String
            return firstvalue
