-
Notifications
You must be signed in to change notification settings - Fork 0
/
normalize.py
492 lines (388 loc) · 12.9 KB
/
normalize.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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
#!/usr/bin/python
import sys
import psycopg2
import json
from itertools import product
debug=False
checkInput=True
pksuccess=False
_1nfsuccess=False
_2nfsuccess=False
_3nfsuccess=False
bcnfsuccess=False
sqlStr=""
output=""
def syntaxError(sqlStr,output):
print("Invalid Input")
output=output+": Invalid Input"+"\n"
saveOutput(output)
saveSql(sqlStr)
quit()
def syntaxErrort(t,sqlStr,output):
print(t+": Invalid Input")
output=output+t+": Invalid Input"+"\n"
saveOutput(output)
saveSql(sqlStr)
quit()
def saveOutput(txt):
with open('nf.txt', 'a') as fout:
if fout.tell() == 0:
fout.write(txt)
else:
fout.write("\n")
fout.write(txt)
def saveSql(txt):
fsql=None
with open('nf.sql', 'a') as fsql:
fsql.write(txt)
if debug: print("")
if debug: print ("Arguments Number:", len(sys.argv), " parts.")
if debug: print ("List of Arguments:", str(sys.argv))
if (len(sys.argv)!=2) :
syntaxError(sqlStr,output)
arg=sys.argv[1]
if debug: print("")
if debug: print ("Argument :", arg)
parts=arg.split(";")
if debug: print ("Argument splited size : ", len(parts), " parts.")
if debug: print ("Argument splited:", str(parts))
if len(parts)!=3:
syntaxError(sqlStr,output)
tableParts=parts[0].split("=")
pkParts=parts[1].split("=")
columnsParts=parts[2].split("=")
if len(tableParts)!=2 :
syntaxError(sqlStr,output)
if len(pkParts)!=2 or len(columnsParts)!=2 :
syntaxErrort(tableParts[1],sqlStr,output)
if len(tableParts[1])==0 or len(pkParts[1])==0 or len(columnsParts[1])==0 :
syntaxErrort(tableParts[1],sqlStr,output)
table=tableParts[1]
pk=pkParts[1]
pks=pk.split(",")
columns=columnsParts[1]
columnsArr=columns.split(",")
def Combinations(A, n, retArr, temp=(), i=0):
if n == 0:
retArr.add(temp)
return
for j in range(i, len(A)):
Combinations(A, n - 1, retArr, temp + (A[j],), j + 1)
columnsCombined = set()
Combinations(columnsArr,2, columnsCombined)
pkcolumnsCombined = list(product(pks, columnsArr))
if len(pks)>2 :
syntaxErrort(table,sqlStr,output)
if debug: print("")
if debug: print ("table :", table)
if debug: print ("pk :", pk," => ",pks)
if debug: print ("columns :", columns," => ",columnsArr)
if(debug):print("Columns Combined :",str(columnsCombined))
if(debug):print("Pk,Columns Combined :",str(pkcolumnsCombined))
if debug: print("")
credentials = None
try:
with open('creds.json') as f:
credentials = json.load(f)
except OSError:
print ("Could not open file creds.json")
quit()
except ValueError:
print ("parsing json failed")
quit()
conn = None
try:
conn = psycopg2.connect(
dbname=credentials.get('database'),
host=credentials.get('host'),
user=credentials.get('user'),
password=credentials.get('password')
)
except (Exception, psycopg2.Error) as error:
print("connection to database failed" , error)
quit()
print("connection to database : success")
#Check if Table Exists
if(checkInput):
try:
cursor = conn.cursor()
query = "SELECT * FROM information_schema.tables WHERE table_schema = 'public' AND table_name = '"+table+"'"
sqlStr=sqlStr+query+"\n\n";
if debug: print("")
if debug: print("Check if Table Exists")
if debug: print("")
cursor.execute(query)
records = cursor.fetchall()
if len(records)==0:
print("")
print("Table ",table+" does not exists in database")
print("")
cursor.close()
conn.close()
quit()
cursor.close()
except (Exception, psycopg2.Error) as error:
print("Error while Testing Table exits or not ", error)
cursor.close()
conn.close()
quit()
if(debug):print("")
if(debug):print("Table "+table+" exists in database")
if(debug):print("")
#Check if Column Exists
errors=[]
allColumns=pks+columnsArr
for c in allColumns:
try:
cursor = conn.cursor()
query = "SELECT * FROM information_schema.columns WHERE table_schema = 'public' AND table_name = '"+table+"'and column_name='"+c+"';"
sqlStr=sqlStr+query+"\n\n";
cursor.execute(query)
records = cursor.fetchall()
if len(records)==0:
errors.append("column "+c+" does not exist")
else:
if(debug):print("column "+c+" exists")
cursor.close()
except (Exception, psycopg2.Error) as error:
print("Error while Testing Column exits or not ", error)
cursor.close()
conn.close()
quit()
for l in errors:
print(l)
if(len(errors)>0):
cursor.close()
conn.close()
quit()
if(debug):print("")
if debug: print("")
if debug: print("Check Empty and single row table")
if debug: print("")
#test Empty and single row table
try:
cursor = conn.cursor()
query = "select * from "+table
sqlStr=sqlStr+query+"\n\n";
if debug: print("")
if debug: print("Check if PK Valid")
if debug: print("")
cursor.execute(query)
records = cursor.fetchall()
if len(records)==0:
print(table+": Empty Table")
output=output+table+": Empty Table"+"\n"
cursor.close()
conn.close()
saveOutput(output)
saveSql(sqlStr)
quit()
elif len(records)==1:
print(table+": Single Row Table")
output=output+table+": Single Row Table"+"\n"
saveOutput(output)
saveSql(sqlStr)
cursor.close()
conn.close()
quit()
except (Exception, psycopg2.Error) as error:
print("Error while Testing if empty or single row", error)
cursor.close()
conn.close()
quit()
print(table)
output=output+table+"\n"
#test Primary Keys
try:
cursor = conn.cursor()
query = "select * from (SELECT "+pk+",count(*) as cnt FROM "+table+" group by "+pk+") t1 where t1.cnt>1"
sqlStr=sqlStr+query+"\n\n";
if debug: print("")
if debug: print("Check if PK Valid")
if debug: print("")
cursor.execute(query)
records = cursor.fetchall()
if len(records)==0:
print("pk Y")
output=output+"pk Y"+"\n"
pksuccess=True
else:
print("pk N")
output=output+"pk N"+"\n"
pksuccess=False
cursor.close()
except (Exception, psycopg2.Error) as error:
print("Error while Testing if PK is valid", error)
cursor.close()
conn.close()
quit()
if(debug):print("")
#test 1NF
try:
cursor = conn.cursor()
query = "select * from (SELECT "+pk+","+columns+",count(*) as cnt FROM "+table+" group by "+pk+","+columns+") t1 where t1.cnt>1"
sqlStr=sqlStr+query+"\n\n";
if debug: print("")
if debug: print("Check 1NF")
if debug: print("")
cursor.execute(query)
records = cursor.fetchall()
if len(records)==0 :
print("1nf Y")
output=output+"1nf Y"+"\n"
_1nfsuccess=True
else:
print("1nf N")
output=output+"1nf N"+"\n"
_1nfsuccess=False
cursor.close()
except (Exception, psycopg2.Error) as error:
print("Error while Testing if PK is valid", error)
cursor.close()
conn.close()
quit()
failedpk1=0
failedpk2=0
if(debug):print("")
#test 2NF
if (len(pks)>=1 and _1nfsuccess and pksuccess):
try:
for c in columnsArr:
cursor = conn.cursor()
if debug: print("Check if 2NF : "+pks[0]+" column "+c)
query = "select * from (SELECT "+pks[0]+",count(Distinct "+c+") as cnt FROM "+table+" group by "+pks[0]+") t1 where t1.cnt>1"
sqlStr=sqlStr+query+"\n\n";
if debug: print(query)
cursor.execute(query)
records = cursor.fetchall()
if len(records)>0:
if(debug):print("result : True")
else:
failedpk1=failedpk1+1
if(debug):print("result : False")
cursor.close()
except (Exception, psycopg2.Error) as error:
print("Error while Testing if 2NF is valid", error)
cursor.close()
conn.close()
quit()
if (len(pks)>=2 and _1nfsuccess and pksuccess):
try:
for c in columnsArr:
cursor = conn.cursor()
if debug: print("Check if 2NF : "+pks[1]+" column "+c)
query = "select * from (SELECT "+pks[1]+",count(Distinct "+c+") as cnt FROM "+table+" group by "+pks[1]+") t1 where t1.cnt>1"
sqlStr=sqlStr+query+"\n\n";
if debug: print(query)
cursor.execute(query)
records = cursor.fetchall()
if len(records)>0:
if(debug):print("result : True")
else:
if(debug):print("result : False")
failedpk2=failedpk2+1
cursor.close()
except (Exception, psycopg2.Error) as error:
print("Error while Testing if 2NF is valid", error)
cursor.close()
conn.close()
quit()
if pksuccess:
if len(pks)>=2 :
if (failedpk1==0 and failedpk2==0) and _1nfsuccess :
print("2nf Y")
output=output+"2nf Y"+"\n"
_2nfsuccess=True
else:
print("2nf N")
output=output+"2nf N"+"\n"
_2nfsuccess=False
else:
print("2nf Y")
output=output+"2nf Y"+"\n"
_2nfsuccess=True
else:
print("2nf N")
output=output+"2nf N"+"\n"
_2nfsuccess=False
failedc=0
if(debug):print("")
#test 3NF
if (_1nfsuccess and _2nfsuccess):
try:
for c in columnsCombined:
cursor = conn.cursor()
if debug: print("Check if 3NF : "+c[0]+" => "+c[1])
query = "select * from (SELECT "+c[0]+",count(Distinct "+c[1]+") as cnt FROM "+table+" group by "+c[0]+") t1 where t1.cnt>1"
sqlStr=sqlStr+query+"\n\n";
cursor.execute(query)
records = cursor.fetchall()
if len(records)>0:
if(debug):print("result : True")
else:
failedc=failedc+1;
if(debug):print("result : False")
cursor.close()
cursor = conn.cursor()
if debug: print("Check if 3NF : "+c[1]+" => "+c[0])
query = "select * from (SELECT "+c[1]+",count(Distinct "+c[0]+") as cnt FROM "+table+" group by "+c[1]+") t1 where t1.cnt>1"
sqlStr=sqlStr+query+"\n\n";
cursor.execute(query)
records = cursor.fetchall()
if len(records)>0:
if(debug):print("result : True")
else:
failedc=failedc+1;
if(debug):print("result : False")
cursor.close()
except (Exception, psycopg2.Error) as error:
print("Error while Testing if 3NF is valid", error)
cursor.close()
conn.close()
quit()
if failedc==0 and _1nfsuccess and _2nfsuccess:
print("3nf Y")
output=output+"3nf Y"+"\n"
_3nfsuccess=True
else:
print("3nf N")
output=output+"3nf N"+"\n"
_3nfsuccess=False
failedc=0
if(debug):print("")
#test bcnf
if (_1nfsuccess and _2nfsuccess and _3nfsuccess):
try:
for c in pkcolumnsCombined:
cursor = conn.cursor()
if debug: print("Check if BCNF : "+c[1]+" => "+c[0])
query = "select * from (SELECT "+c[1]+",count(Distinct "+c[0]+") as cnt FROM "+table+" group by "+c[1]+") t1 where t1.cnt>1"
sqlStr=sqlStr+query+"\n\n";
cursor.execute(query)
records = cursor.fetchall()
if len(records)>0:
if(debug):print("result : True")
else:
failedc=failedc+1;
if(debug):print("result : False")
cursor.close()
except (Exception, psycopg2.Error) as error:
print("Error while Testing if BCNF is valid", error)
cursor.close()
conn.close()
quit()
if failedc==0 and _1nfsuccess and _2nfsuccess and _3nfsuccess:
print("bcnf Y")
output=output+"bcnf Y"+"\n"
bcnfsuccess=True
else:
print("bcnf N")
output=output+"bcnf N"+"\n"
bcnfsuccess=False
if conn:
conn.close()
if(debug):print("Connection to database is closed")
print("")
#write Files
saveOutput(output)
saveSql(sqlStr)