-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2018201100.py
More file actions
361 lines (320 loc) · 11.1 KB
/
Copy path2018201100.py
File metadata and controls
361 lines (320 loc) · 11.1 KB
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
import sys
import csv
import os
import sqlparse
from collections import OrderedDict
identifiers = []
database_dict = {}
is_distinct = False
def read_metadata():
if not os.path.exists('./files/metadata.txt'):
print("[System Error]: Metadata File Not Found.\n")
sys.exit(1)
with open("./files/metadata.txt", "r") as file:
flag = 0
for line in file:
line = line.strip()
if line == "<begin_table>":
flag = 1
continue
if flag:
table = line
database_dict[table] = []
flag = 0
continue
if flag == 0 and line != "<end_table>":
database_dict[table].append(line)
def validate_columns(column_list, table_list):
cols_dict = {}
for table in table_list:
for col_list in database_dict[table.strip()]:
for col in col_list:
if col in list(cols_dict.keys()):
cols_dict[col] = 2
else:
cols_dict[col] = 1
for col in column_list:
if cols_dict[col] == 2:
print("[Attribute Error]: Ambigous Attribute.\n")
sys.exit(1)
valid_cols = {}
offset = 0
for table in table_list:
for col in column_list:
if col not in list(valid_cols.keys()):
valid_cols[col] = -1
if col in database_dict[table.strip()]:
index = database_dict[table.strip()].index(col)
valid_cols[col] = index + offset
offset += len(database_dict[table.strip()])
if -1 in list(valid_cols.values()):
return -1
else:
return valid_cols
def check_valid_agg_syntax(attribute_list):
agg_funcs = ['sum', 'max', 'min', 'avg']
valid = True
agg_dict = {}
for item in attribute_list.split(", "):
if len(item) > 3 and item[0:3] in agg_funcs:
agg_dict[item[4:-1]] = item[0:3]
else:
valid = False
break
if not valid:
return valid
else:
return agg_dict
def max_agg_func(col_name, table_name):
if not os.path.exists('./files/' + table_name + ".csv"):
print("[Table Error]: No Table Found.\n")
sys.exit()
col_index = database_dict[table_name].index(col_name)
with open('./files/' + table_name + ".csv") as file:
row = []
for line in file:
row.append(line.strip().split(",")[col_index])
big = float('-inf')
for item in row:
if int(item) > big:
big = int(item)
return big
def min_agg_func(col_name, table_name):
if not os.path.exists('./files/' + table_name + ".csv"):
print("[Table Error]: No Table Found.\n")
sys.exit()
col_index = database_dict[table_name].index(col_name)
with open('./files/' + table_name + ".csv") as file:
row = []
for line in file:
row.append(line.strip().split(",")[col_index])
small = float('inf')
for item in row:
if int(item) < small:
small = int(item)
return small
def sum_agg_func(col_name, table_name):
if not os.path.exists('./files/' + table_name + ".csv"):
print("[Table Error]: No Table Found.\n")
sys.exit()
col_index = database_dict[table_name].index(col_name)
with open('./files/' + table_name + ".csv") as file:
row = []
for line in file:
row.append(line.strip().split(",")[col_index])
summation = 0
for item in row:
summation += int(item)
return summation
def avg_agg_func(col_name, table_name):
if not os.path.exists('./files/' + table_name + ".csv"):
print("[Table Error]: No Table Found.\n")
sys.exit()
col_index = database_dict[table_name].index(col_name)
with open('./files/' + table_name + ".csv") as file:
row = []
for line in file:
row.append(line.strip().split(",")[col_index])
avg = 0
for item in row:
avg += int(item)
return avg/len(row)
def project_join_query(table, join_cols):
join_dict = OrderedDict()
for item in join_cols:
table_name, col_name = item.split('.')
join_dict[table_name] = col_name
indices = []
ignore_col = [list(join_dict.keys())[1], join_dict[list(join_dict.keys())[1]]]
offset = 0
for table_name in join_dict.keys():
indices.append(database_dict[table_name].index(join_dict[table_name]) + offset)
offset += len(database_dict[table_name])
temp_table = []
for row in table:
if row[indices[0]] == row[indices[1]]:
row.pop(indices[1])
temp_table.append(row)
header = []
flag = 0
for key in database_dict:
if key == ignore_col[0]:
flag = 1
for item in database_dict[key]:
if flag and item == ignore_col[1]:
continue
else:
header.append(key + '.' + item)
print(",".join(header) + "\n")
for row in temp_table:
for item in row:
if row.index(item) == len(row)-1:
print(str(item), end = "")
else:
print(str(item) + ",", end = "")
print()
def project_aggregation(agg_dict, table_name):
valid = True
for key in list(agg_dict.keys()):
if key not in database_dict[table_name]:
valid = False
break
if valid:
final_table = []
header = []
for key in agg_dict:
if agg_dict[key].lower() == 'max':
temp_table = max_agg_func(key, table_name)
final_table.append(str(temp_table))
header.append(table_name + "." + key)
elif agg_dict[key].lower() == 'min':
temp_table = min_agg_func(key, table_name)
final_table.append(str(temp_table))
header.append(table_name + "." + key)
elif agg_dict[key].lower() == 'sum':
temp_table = sum_agg_func(key, table_name)
final_table.append(str(temp_table))
header.append(table_name + "." + key)
else:
temp_table = avg_agg_func(key, table_name)
final_table.append(str(temp_table))
header.append(table_name + "." + key)
print("\t".join(header))
print("\t\t".join(final_table))
else:
print("[Attribute Error]: Invalid Arguments.\n")
sys.exit(1)
def project_some_cols(index_list, table, table_list):
header = []
for col in list(index_list.keys()):
for table_name in table_list:
if col in database_dict[table_name.strip()]:
header.append(table_name + '.' + col)
break
print("\t".join(header) + "\n")
if is_distinct:
x = str()
distinct_set = set()
for row in table:
for index in index_list.values():
x += (str(row[index]) + "\t\t")
distinct_set.add(x)
x = str()
for item in distinct_set:
print(item)
else:
for row in table:
for index in index_list.values():
print(str(row[index]) + "\t\t", end = "")
print()
def project_table(table, header):
for col_name in header:
print(col_name + "\t", end = "")
print()
for row in table:
for item in row:
print(str(item) + ",\t", end = "")
print()
print()
def make_table(table_list):
table_name = table_list + '.csv'
if not os.path.exists('./files/'+table_name):
return -1
result = []
with open('./files/'+table_name, "r") as fopen:
for line in fopen:
result.append(list(map(int, line.strip().split(','))))
return result
def cross_product(table_list):
table = make_table(table_list[0].strip())
if table == -1:
return -1
for item in range(1, len(table_list)):
temp_table = []
next_table = make_table(table_list[item].strip())
if next_table == -1:
return -1
for x in range(len(table)):
for y in range(len(next_table)):
temp_table.append(table[x] + next_table[y])
table = temp_table
return table
def process_query(query):
# Todo - Check for aggregation functions
if identifiers[3] in ['where', 'WHERE']:
print("[Table Error]: No Table Specified.\n")
sys.exit(1)
table_list = identifiers[3].strip().split(',')
if len(table_list) == 1:
table = make_table(table_list[0])
else:
table = cross_product(table_list)
if table == -1:
print("[Table Error]: No Table Found.\n")
sys.exit(1)
if '*' in identifiers[1] and len(identifiers[1].split(', ')) == 1:
if 'where' in identifiers[4]:
valid_query = True
join_cols = identifiers[4].strip().split()[1].split('=')
for item in join_cols:
table_name, col_name = item.split('.')
if col_name not in database_dict[table_name]:
valid_query = False
break
project_join_query(table, join_cols)
else:
header = []
for table_name in table_list:
for column in database_dict[table_name.strip()]:
header.append(table_name + "." + column + ",")
project_table(table[:], header)
elif '*' not in identifiers[1] and len(identifiers[1].split(", ")) >= 1:
if '(' not in identifiers[1]:
column_list = identifiers[1].split(", ")
index_list = validate_columns(column_list, table_list)
if index_list == -1:
print("[Attribute Error]: Invalid Arguments.\n")
sys.exit(1)
else:
project_some_cols(index_list, table, table_list)
else:
agg = check_valid_agg_syntax(identifiers[1])
if agg is not False:
project_aggregation(agg, table_list[0].strip())
else:
return -1
else:
return -1
def parse_query(query):
global is_distinct
if ';' in query:
query = query.strip(';')
else:
print("[Query Error]: Invalid Query.\n")
sys.exit(1)
parsed_query = sqlparse.parse(query)[0].tokens
if sqlparse.sql.Statement(parsed_query).get_type() != 'SELECT':
print("[Query Error]: Non - SELECT Query.\n")
sys.exit(1)
else:
id = sqlparse.sql.IdentifierList(parsed_query).get_identifiers()
for item in id:
if str(item) != ';':
identifiers.append(str(item))
if 'distinct' in identifiers:
is_distinct = True
identifiers.pop(1)
if len(identifiers) < 4:
print("[Query Error]: Invalid Query.\n")
sys.exit(1)
read_metadata()
status = process_query(query)
if status == -1:
print("[Query Error]: Invalid Query.")
sys.exit(1)
if len(sys.argv) != 2:
print("[System Error]: Invalid Number of Arguments.")
print("Usage - python3 2018201100.py <query;>\n")
sys.exit(1)
cmd_line_input = sys.argv[1]
parse_query(cmd_line_input)