{-# LANGUAGE TemplateHaskell #-}

module SqlExpr where

import Language.Haskell.TH

import Database.HDBC
import Database.HDBC.ODBC

compileSql :: String -> String -> ExpQ
compileSql dsn sqlExpr =
    do desc <- runIO (connectDB dsn sqlExpr)
       [| \dsn -> do rows <- fetchRows dsn sqlExpr
                     return $ map ( $(fromRow desc) ) rows |]

-- Evaluated at run-time
fetchRows :: Connection -> String -> IO [[SqlValue]]
fetchRows c sqlExpr =
    do preStmt <- prepare c sqlExpr          `myCatch` "calling prepare"
       execute preStmt []                    `myCatch` "executing prepared statement"
       fetchAllRows preStmt                  `myCatch` "fetch all rows"

-- Evaluated both compile & runtime
myCatch :: IO a -> String -> IO a       
myCatch command doing =
    command `catchSql` (\e -> error ("Exception when trying \"" ++ doing ++ "\" : " ++ seErrorMsg e))

-- The rest is evaluated only at compile-time
connectDB :: String -> String -> IO [SqlTypeId]
connectDB dsn sqlExpr =
    do c <- connectODBC dsn                  `myCatch` "connecting to DB"
       preStmt <- prepare c sqlExpr          `myCatch` "calling prepare"
       execute preStmt []                    `myCatch` "executing prepared statement"
       y <- fetchRow preStmt                 `myCatch` "fecthing a row"
       description <- describeResult preStmt `myCatch` "describing result"
       let desc = map (colType . snd) description
       disconnect c                          `myCatch` "disconnecting"
       return desc

fromRow :: [SqlTypeId] -> ExpQ
fromRow xs = do es <- mapM fromColumn xs
                names <- mapM (\i -> newName ("x" ++ show i)) [0..(length es - 1)]
                return $ LamE [ListP (map VarP names)] (TupE $ map (\(e, n) -> AppE e (VarE n)) $ zip es names)

fromColumn :: SqlTypeId -> ExpQ
fromColumn SqlIntegerT = [| readInteger |]
fromColumn SqlVarCharT = [| readString |]
-- missing a lot of types here - but this is just a proff of concept

readInteger :: SqlValue -> Integer
readInteger (SqlString s) = read s

readString :: SqlValue -> String
readString (SqlString s) = s

