module SQLParser where
import Text.Parsec.String (Parser)
import Text.Parsec.Error (ParseError)
import Text.Parsec (parse)
import Text.ParserCombinators.Parsec.Combinator (eof)
import Control.Applicative ((<*),(<$>), (*>), (<|>),(<$),(<*>))
import Funcs
import ExpressionParser
import QueryParser
import InsertParser
import CreateParser
import DeleteParser
import Database
import Data.Map (Map)
import qualified Data.Map as Map
data SQLExpr = SELECT QueryExpr
| INSERT InsertExpr
| CREATE CreateExpr
| DELETE DeleteExpr
deriving (Eq, Show)
data ResType = DB (Maybe Database)
| OUT ([[(Int,String, Datatype, String)]])
| ERROR String deriving(Eq,Show)
sqlExpr :: Parser SQLExpr
sqlExpr = (SELECT <$> queryExpr ) <|> (INSERT <$> insertExpr) <|> (CREATE <$> createExpr) <|> (DELETE <$> deleteExpr)
evaluateSQL :: Either ParseError SQLExpr -> ResType -> ResType
evaluateSQL (Right expr) (DB db) = do
case expr of
SELECT e -> OUT (evaluateQuery (Right e) db)
INSERT e -> DB (evaluateInsert (Right e) db)
CREATE e -> DB (evaluateCreate (Right e) db)
DELETE e -> DB (evaluateDelete (Right e) db)
evaluateSQL (Left error) db = ERROR (show error)
getHeaders :: [(Int,String,Datatype,String)] -> String
getHeaders [] = ""
getHeaders ((d,a,b,c) : xs) = (a++" ("++(show b)++"), ")++(getHeaders xs)
getRow :: [(Int,String,Datatype,String)] -> String
getRow [] = ""
getRow ((d,a,b,c) : xs) = (c++", ")++(getRow xs)
getRows :: [[(Int,String,Datatype,String)]] -> IO ()
getRows [] = putStr ""
getRows (x: xs) = putStrLn((let (a,b,c,d) = head x in show a++", ")++getRow x) *> (getRows xs)
queryPrinter :: ResType -> IO ()
queryPrinter (OUT output) = do
case output of
[] -> print("")
otherwise -> putStrLn("------------------------------------------------------------")
*> putStrLn("PK, "++getHeaders (head output))
*> putStrLn("------------------------------------------------------------")
*> (getRows output)