-
Notifications
You must be signed in to change notification settings - Fork 2
/
query_parser.py
189 lines (169 loc) · 5.51 KB
/
query_parser.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import sqlparse
import copy
import re
import time
logical_opt = ['AND', 'OR', '(', ')']
compare_opt = ['>=', '<=', '<>', '>', '<', '=', 'LIKE']
def get_condition(where):
loglst = [l for l in where.split(' ') if l in logical_opt]
newlst = copy.deepcopy(loglst)
if '(' in newlst and ')' in newlst:
newlst.remove('(')
newlst.remove(')')
where = where.replace("(", "")
where = where.replace(")", "")
if not newlst:
return loglst, [where]
else:
if len(newlst) > 1:
for log in newlst[1:]:
where = where.replace(log, newlst[0])
return loglst, [i.strip() for i in where.split(newlst[0])]
def split_condition(s):
for sep in compare_opt:
if sep in s:
lst = []
for i in s.split(sep):
# start from NOT
if i.startswith("NOT"):
lst.append('NOT')
i = i[4:]
i = i.strip()
# string or character
if i.startswith("'") and i.endswith("'"):
lst.append([i[1:-1]])
# attribute without rename or integers
elif not '.' in i:
lst.append([i])
else:
# float number
test = i.replace(".", "")
if test.isnumeric():
lst.append([i])
# attribute with rename
else:
new_attr = i.split('.')
lstitem = []
lstitem.append(new_attr[0].strip())
lstitem.append(new_attr[1].strip())
lst.append(lstitem)
return lst, sep
break
return [], ''
def reverse_not(opt):
if opt == '<':
newopt = '>='
elif opt == '>':
newopt = '<='
elif opt == '<=':
newopt = '>'
elif opt == '>=':
newopt = '<'
elif opt == '=':
newopt = '<>'
elif opt == '<>':
newopt = '='
else:
newopt = 'NOT LIKE'
return newopt
# Help function to order the parenthese function
def sort_order(lst, leftside, inside, rightside, num):
order = []
if not leftside:
for n in range(len(lst)):
index = lst.index(lst[n])
order.append(index)
else:
for i in leftside:
order.append(i + num)
for j in range(len(inside)):
order.append(j)
for k in rightside:
order.append(k)
newlist = []
for m in range(len(order)):
index = order.index(m)
newlist.append(lst[index])
return newlist
def parentheses(keyword, conds):
left = keyword.index('(')
right = keyword.index(')')
keyword.remove('(')
keyword.remove(')')
num_inside = right - left - 1
inside = []
leftside = []
rightside = []
for i in range(0, left):
leftside.append(i)
for j in range(left, right - 1):
inside.append(j)
for z in range(right - 1, len(keyword)):
rightside.append(z)
newkey = sort_order(keyword, leftside, inside, rightside, num_inside)
inside2 = [i for i in inside] + [i + 1 for i in inside]
leftside2 = leftside
rightside2 = [j + 1 for j in rightside]
newcond = sort_order(conds, leftside2, inside2, rightside2, num_inside + 1)
return newkey, newcond
def sql_preprocess(query):
if 'DISTINCT' in query:
dist = True
sql = query.replace('DISTINCT', '')
else:
dist = False
sql = query
sql = sqlparse.format(sql)
stmt = sqlparse.parse(sql)[0]
# Select clauses
attrs = str(stmt.tokens[2])
attrs = attrs.split(',')
attribute = []
for i in range(len(attrs)):
if not '.' in attrs[i]:
attribute.append([attrs[i].strip()])
else:
array = []
new_file = attrs[i].split('.')
array.append(new_file[0].strip())
array.append(new_file[1].strip())
attribute.append(array)
# From clauses
file = str(stmt.tokens[6])
file = file.split(',')
files = []
for j in range(len(file)):
file[j] = file[j].strip()
if not ' ' in file[j]:
files.append([file[j]])
else:
array2 = []
new_file = file[j].split(' ')
array2.append(new_file[0].strip())
array2.append(new_file[1].strip())
files.append(array2)
# Where clause conditions, e.q. 'ID = 3'
if 'WHERE' not in sql:
conds = []
keyword = []
else:
wherestr = str(stmt.tokens[-1])
where = str(re.findall('WHERE (.*);', wherestr))[2:-2]
keyword, condition = get_condition(where)
n = len(files)
if n == 1:
conds = []
for c in condition:
value, opt = split_condition(str(c))
conds.append(value + [opt])
else:
conds = []
for c in condition:
value, opt = split_condition(str(c))
if value[0] == 'NOT':
value.remove('NOT')
opt = reverse_not(opt)
conds.append(value + [opt])
if '(' in keyword and ')' in keyword:
keyword, conds = parentheses(keyword, conds)
return attribute, files, conds, keyword, dist