-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcsv_metadata.py
384 lines (362 loc) · 13 KB
/
csv_metadata.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
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
import csv
import itertools
import os
#dectionary with tablename as key and fields as list in value
metadata = {};
#dictionary with tablename as key and fields as (dictionary with column as key and values as list)
db = {};
def readTable(tablename, table):
with open(tablename + ".csv", 'rb') as csvfile:
tablereader = csv.reader(csvfile, delimiter=',')
for row in tablereader:
row = [int(x) for x in row];
table.append(row);
return table;
def truncateTable(table, db):
if(not db.has_key(table)):
print "Table " + table + " does not exists";
return -1;
else:
db[table] = [];
toAddLines = '';
with open(table + '.csv', 'wb') as table_file:
table_file.write(toAddLines);
return 0;
def printRows(header, rows):
# import pdb; pdb.set_trace();
for col_name in header:
print col_name,
print '\t',
# print "\t".join(header);
print '';
for row in rows:
for col in row:
print col,
print '\t',
print '';
# print "\t".join(row[0]);
def colNoFromColName(table_column, tables, metadata):
table_and_column = table_column.split(".");
if len(table_and_column) == 2:
table_name = table_and_column[0]
col_name = table_and_column[1]
col_no = 0;
i=0;
flag = 0;
j = 0;
ret_col_no = 0;
flag = 0;
for table in tables:
if table_name == table:
if col_name in metadata[table]:
col_no = metadata[table].index(col_name);
j, ret_col_no = (i, col_no);
flag = 1;
else:
print col_name + " does not exist in " + table_name;
return (-1, -1);
else:
i += 1;
if flag:
return (j, ret_col_no);
else:
print "Column " + col_name + " does not exist in table " + table_name;
else:
col_name = table_and_column[0]
col_no = 0;
i=0;
flag = 0;
j = 0;
ret_col_no = 0;
flag = 0;
for table in tables:
if col_name in metadata[table]:
col_no = metadata[table].index(col_name);
j, ret_col_no = (i, col_no);
if flag:
print "Multiple columns in give tables have name " + col_name;
return (-1, -1);
flag = 1;
else:
i += 1;
if flag:
return (j, ret_col_no);
else:
print "Column " + col_name + " does not exist in given table(s)";
return (-1, -1);
def executeInsert(table, values, db, metadata):
values = [str(value) for value in values]
if metadata.has_key(table):
if len(metadata[table]) == len(values):
with open(table + '.csv', 'a') as table_file:
toAddLine = ','.join(values)
toAddLine += '\r\n';
table_file.write(toAddLine);
db[table].append([value for value in values]);
return 0;
else:
print "number of values to be inserted should be " + str(len(metadata[table]));
return -1;
else:
print "table " + table + " does not exist";
return -1;
def whereClause(row, conds, tables, metadata):
res_where = []
for cond in conds:
if isinstance(cond,str):
res_where.append(cond);
continue;
if not (cond[0].isdigit() or (cond[0].startswith('-') and cond[0][1:].isdigit())):
i, col_no = colNoFromColName(cond[0], tables, metadata);
if not (i == -1 and col_no == -1):
lhs = row[i][col_no];
else:
print "column " + cond[0] + " does not exist";
return -1;
else:
lhs = int(cond[0])
if not (cond[2].isdigit() or (cond[2].startswith('-') and cond[2][1:].isdigit())):
i, col_no = colNoFromColName(cond[2], tables, metadata);
if not(i == -1 and col_no == -1):
rhs = row[i][col_no];
else:
print "column " + cond[2] + " does not exist";
return -1;
else:
rhs = int(cond[2])
eq = ["=", "eq"];
ne = ["!=", "ne"];
lt = ["<", "lt"];
le = ["<=", "le"];
gt = [">", "gt"];
ge = [">=", "ge"];
# print lhs, rhs
if(cond[1] in eq):
res_where.append(lhs == rhs);
elif(cond[1] in ne):
res_where.append(lhs != rhs);
elif(cond[1] in lt):
res_where.append(lhs < rhs);
elif(cond[1] in le):
res_where.append(lhs <= rhs);
elif(cond[1] in gt):
res_where.append(lhs > rhs);
elif(cond[1] in ge):
res_where.append(lhs >= rhs);
print lhs, rhs
return res_where
def executeDelete(tables, where, conds, db, metadata):
for table in tables:
if not db.has_key(table):
print "table " + table + " does not exist";
return -1;
db_tables = [db[table] for table in tables]
metadata_tables = [metadata[table] for table in tables]
rows = []
for row in itertools.product(*db_tables):
res_where = [];
if where == True:
res_where = whereClause(row, conds, tables, metadata);
if isinstance(res_where,int) and res_where == -1:
return -1;
if eval(' '.join([ str(z) for z in res_where])) == True:
continue;
row = [i for i in row[0]];
rows.append(row);
print row, res_where
if(truncateTable(tables[0],db) == -1):
return -1;
else:
for row in rows:
if (executeInsert(tables[0],row, db, metadata) == -1):
return -1;
return 0;
def executeSelect(allColumns, columns, tables, where, conds, db, metadata):
# print allColumns
# print columns
# print tables
# print where
# print conds
for table in tables:
if not db.has_key(table):
print "table " + table + " does not exist";
return -1;
db_tables = [db[table] for table in tables]
metadata_tables = [metadata[table] for table in tables]
retRows = []
header = []
headerMap = {};
specialToken = 0;
specialTokens = ["MAX", "MIN", "AVG", "SUM", "DISTINCT"];
specialFlag = 0;
if columns[0].upper() in specialTokens :
columns[0] = columns[0].upper()
specialToken = 1;
headerMap[columns[2]] = colNoFromColName(columns[2], tables, metadata);
if(headerMap[columns[2]] == (-1, -1)):
return -1;
if allColumns == 1:
for table in tables:
for field in metadata[table]:
header.append(table+"."+field);
else:
if columns[0] == "DISTINCT":
header = [columns[2]]
elif specialToken == 0:
header = [column for column in columns]
else :
header = [''.join(columns)]
if specialToken == 0:
for column in header:
headerMap[column] = colNoFromColName(column, tables, metadata);
if(headerMap[column] == (-1, -1)):
return -1;
count = 0;
for row in itertools.product(*db_tables):
# print row
res_where = [];
if where == True:
res_where = whereClause(row, conds, tables, metadata);
if isinstance(res_where,int) and res_where == -1:
return -1;
# print row, res_where
if eval(' '.join([ str(z) for z in res_where])) == False:
continue;
retRow = []
for column in header:
# print headerMap[column]
# print row[headerMap[column][0]][headerMap[column][1]]
if specialToken == 0 or columns[0] == "DISTINCT":
retRow.append(row[headerMap[column][0]][headerMap[column][1]]);
else:
val = row[headerMap[columns[2]][0]][headerMap[columns[2]][1]];
if columns[0] == "MAX":
if specialFlag == 1:
specialValue = max(specialValue,val)
else:
specialValue = val;
specialFlag = 1;
elif columns[0] == "MIN":
if specialFlag == 1:
specialValue = min(specialValue,val)
else:
specialValue = val;
specialFlag = 1;
elif columns[0] == "AVG" or "SUM":
if specialFlag == 1:
specialValue += val
else:
specialValue = val;
specialFlag = 1;
count += 1;
if specialToken == 0 or columns[0] == "DISTINCT":
retRows.append(retRow)
# import pdb; pdb.set_trace()
if specialToken == 1 and columns[0] != "DISTINCT":
retRows = []
if specialFlag == 1:
if columns[0] == "MAX" or columns[0] == "MIN" or columns[0] == "SUM":
retRows.append([specialValue])
elif columns[0] == "AVG":
retRows.append([specialValue/count]);
else:
print "No columns found that satisfy Where Clause Or No Columns in given table(s)"
return -1;
if columns[0] == "DISTINCT":
distinctRetRows = []
for row in retRows:
if row not in distinctRetRows:
distinctRetRows.append(row)
printRows(header, distinctRetRows);
else:
printRows(header, retRows);
# import pdb; pdb.set_trace()
return 0;
def execute(tokens, db, metadata):
if(len(tokens) > 0):
if(tokens[0] == 'exit'):
return exit();
elif(tokens[0] == 'select'):
allColumns = 0;
where = False;
columns = tokens.columns
if(columns == '*'):
allColumns = 1;
tables = tokens.tables
conds = tokens.conds
if conds != '':
where = True;
# import pdb; pdb.set_trace()
return executeSelect(allColumns, columns, tables, where, conds, db, metadata);
elif(tokens[0] == 'delete from'):
table = tokens.table;
tables = [table]
values = tokens.intValues;
conds = tokens.conds
where = False;
if conds != '':
where = True;
executeDelete(tables, where, conds, db, metadata);
return 0;
elif(tokens[0] == 'insert into'):
table = tokens.table;
values = tokens.intValues;
executeInsert(table, values, db, metadata);
return 0;
elif(tokens[0] == "create table"):
table = tokens.table;
if(metadata.has_key(table)):
print "Table " + table + " already exists";
return -1;
else:
fields = [field for field in tokens.fields if field != "int"];
db, metadata = addTable(table, fields);
return 0;
elif(tokens[0] == "truncate table"):
table = tokens.table
return truncateTable(table, db);
elif(tokens[0] == "drop table"):
table = tokens.table
if(not db.has_key(table)):
print "Table " + table + " does not exists";
return -1;
else:
db.pop(table,None);
metadata.pop(table,None);
toAddLines = '';
os.remove(table+'.csv');
with open('metadata.txt', 'wb') as table_file:
table_file.write(toAddLines);
for table in metadata:
addTable(table,metadata[table]);
return 0;
def readMetadataAndConstructDb():
with open("metadata.txt") as metadata_file:
metadata_lines = metadata_file.readlines()
key = "";
metadata_lines = [metadata_line.strip() for metadata_line in metadata_lines];
for i in xrange(0,len(metadata_lines)-1):
if metadata_lines[i] == "<begin_table>":
i += 1;
if i < len(metadata_lines):
tablename = metadata_lines[i];
db[tablename] = [];
readTable(tablename, db[tablename]);
metadata[tablename] = [];
i += 1;
while i < len(metadata_lines) and metadata_lines[i] != "<end_table>":
col_name = metadata_lines[i];
metadata[tablename].append(col_name);
i += 1;
return (db, metadata);
def addTable(tablename, fields):
toAddLines = "";
toAddLines += "\n<begin_table>";
toAddLines += ("\n" + tablename);
for field in fields:
toAddLines += ( "\n" + field);
toAddLines += "\n<end_table>";
open(tablename + '.csv', 'wb');
with open('metadata.txt', 'a') as metadata_file:
metadata_file.write(toAddLines);
return readMetadataAndConstructDb();