· 7 years ago · Dec 07, 2018, 11:58 PM
1import Text.ParserCombinators.ReadP
2import Data.Char (isAlpha)
3import qualified Data.Text as T
4
5tableParser :: ReadP String
6tableParser = do
7 string "create"
8 many1 (satisfy (\x -> x == ' '))
9 --skipSpaces()
10 string "table"
11 many1 (satisfy (\x -> x == ' '))
12 option "" (string "if")
13 many (satisfy (\x -> x == ' '))
14 option "" (string "not")
15 many (satisfy (\x -> x == ' '))
16 option "" (string "exists")
17 many (satisfy (\x -> x == ' '))
18 tableName <- munch1 (\x -> (isAlpha(x) || x == '_') && x /= '(')
19 return tableName
20
21exprParser = do
22 expr1 <- munch (\c -> c /= ';')
23 satisfy (== ';')
24 return expr1
25
26testIt x = do
27 readP_to_S tableParser x
28
29strip :: String -> String
30strip s = T.unpack (T.strip $ T.pack s)
31
32{-
33-}
34parseExpr :: String -> [String]
35parseExpr s =
36 case readP_to_S exprParser s of
37 [] -> []
38 ((found, remaining): _) ->
39 (strip found):(parseExpr remaining)
40
41{-
42 - example to run
43 - map parseTablename (parseExpr "create table if not exists my_table ()\
44 \ ; create table if my_table_again \
45 \ () ;")
46 - > ["my_table", "my_table_again"]
47-}
48parseTablename s =
49 case readP_to_S tableParser s of
50 [] -> ""
51 lst@(_) -> (fst $ last lst)