module Database.MetaHDBC.SimpleSqlParser
    ( simpleSqlParser )
where

import Data.Char
import Data.List(intersperse)

-- varid 	 -> 	 (small {small | large | digit | ' })
-- small 	 -> 	 ascSmall | uniSmall | _

-- |Parses an extended SQL string. The extionsion is that we allow
-- variable-ids after placeholders (question marks). We return the
-- list of identifiers and the SQL string without the variable-ids. If
-- no variable-id is found after a placeholder, the empty string is
-- returned as variable-id.
simpleSqlParser :: String -> ([String], String)
simpleSqlParser sql =
    case splitWhen '?' sql of
      []     -> ([], "")
      (x:xs) -> let (vars, rests) = unzip $ map parseVar xs 
                in (vars, concat $ intersperse "?" (x:rests))

parseVar :: String -> (String, String)   -- (var, rest)
parseVar []     = ("", [])
parseVar (x:xs) | isLower x   = span (\c -> isAlphaNum c || c == '\'') (x:xs)
                | otherwise   = ("", x:xs)

splitWhen :: (Eq a) => a -> [a] -> [[a]]
splitWhen splitter xs
    = case break (== splitter) xs of
        (ys, [])     -> [ys]
        (ys, (_:zs)) -> ys : splitWhen splitter zs