module Kibro.DB
    (query,exec,Kibro.DB.commit
    ,module Database.HDBC)
    where

import Kibro hiding (handleErrors)
import Database.HDBC hiding (commit)
import qualified Database.HDBC as HDBC
import Control.Exception

runSql :: IConnection c 
       => (c -> String -> [SqlValue] -> IO a) -- ^ SQL function.
       -> c                                   -- ^ SQL connection.
       -> String                              -- ^ Query.
       -> [SqlValue]                          -- ^ Parameters.
       -> Kibro c a                           -- ^ Result.
runSql f dbh s vs = io $ handleSql throwSqlError $ f dbh s vs where
    throwSqlError (SqlError _ _ e) =
        throwIO $ AssertionFailed $
                    "SQL error: " ++ show s ++ " " ++ show vs ++ e

query :: IConnection c => String -> [SqlValue] -> Kibro c [[SqlValue]]
query sql values = do
  dbh <- gets con
  runSql quickQuery' dbh sql values

exec :: IConnection c => String -> [SqlValue] -> Kibro c Integer
exec sql values = do
  dbh <- gets con
  runSql run dbh sql values

commit :: IConnection c => Kibro c ()
commit = do
  dbh <- gets con
  io $ HDBC.commit dbh