-
Notifications
You must be signed in to change notification settings - Fork 1
/
db.py
497 lines (454 loc) · 16.1 KB
/
db.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
493
494
495
496
497
#!/usr/bin/env python3
import json
import os
import configparser
from os import path
import sqlite3
import psycopg2
import mysql.connector
from pymongo import MongoClient
from abc import ABC, abstractmethod
class Database(ABC):
@abstractmethod
def connect(self):
pass
@abstractmethod
def fetchall(self):
pass
@abstractmethod
def fetchone(self, row, where = None):
pass
@abstractmethod
def insert(self, row):
pass
@abstractmethod
def delete(self, row):
pass
@abstractmethod
def update(self, row, where = None):
pass
def choose():
config = configparser.ConfigParser()
config.read('heimdall.conf')
dbType = config['DATABASE']['DB_TYPE']
if dbType == "JSON":
dbObj = JSON()
elif dbType == "POSTGRESQL":
dbObj = PostgreSQL()
elif dbType == "SQLITE3":
dbObj = SQLite3()
elif dbType == "MYSQL":
dbObj = MySQL()
elif dbType == "MONGODB":
dbObj = MongoDB()
else:
print(dbType)
raise Exception('Corrupted Config File')
return dbObj
class MySQL(Database):
def connect(self):
try:
config = configparser.ConfigParser()
config.read('heimdall.conf')
dbDetails = config['DATABASE']
con = mysql.connector.connect(
host = dbDetails['MY_HOST'],
port = dbDetails['MY_PORT'],
user = dbDetails['MY_USER'],
password = dbDetails['MY_PASS'],
database = dbDetails['MY_DBNAME'],
)
con.autocommit = True
cur = con.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS invites(invite_code varchar(100) primary key, uses int(10), role_linked varchar(100), role_id varchar(200))')
return con
except Exception as e:
print('Error connecting to MySQL DB',e)
def fetchall(self):
try:
con = self.connect()
cur = con.cursor()
cur.execute('SELECT * FROM invites')
rows = cur.fetchall()
data = []
for row in rows:
data.append({"invite_code": row[0], "uses": row[1],"role_linked": row[2], "role_id": row[3]})
cur.close()
con.close()
return data
except Exception as error:
print(error)
return {}
def fetchone(self, column, where=None):
try:
con = self.connect()
cur = con.cursor()
column = ','.join(column)
if(where == None):
cur.execute(f'SELECT {column} FROM invites')
else:
where_clause = f'WHERE {list(where.keys())[0]} = "{list(where.values())[0]}"'
cur.execute(f'SELECT {column} FROM invites {where_clause}')
rows = cur.fetchall()
data = {'data':[]}
for row in rows:
if(len(row)>1):
data[row[0]]=row[1]
else:
data['data'].append(row[0])
return data
except Exception as e:
print(e)
return {}
def insert(self, data):
try:
con = self.connect()
con.autocommit = True
cur = con.cursor()
cur.execute(f"INSERT INTO invites(invite_code, uses, role_linked, role_id) VALUES('{data['invite_code']}', {data['uses']}, '{data['role_linked']}', '{data['role_id']}')")
con.close()
return True
except mysql.connector.Error as err:
if err.errno == 1146:
self.createMySQLDB()
self.insert(data)
except Exception as error:
print(error)
return False
def update(self, set, where):
try:
con = self.connect()
con.autocommit = True
cur = con.cursor()
cur.execute(f"UPDATE invites SET {list(set.keys())[0]}='{list(set.values())[0]}' WHERE {list(where.keys())[0]}='{list(where.values())[0]}'")
con.close()
return True
except Exception as error:
print(error)
return False
def delete(self, where):
try:
con = self.connect()
con.autocommit = True
cur = con.cursor()
where_clause = f'WHERE {list(where.keys())[0]}="{list(where.values())[0]}"'
cur.execute(f'DELETE FROM invites {where_clause}')
return True
except Exception as e:
print(e)
return False
class PostgreSQL(Database):
def connect(self):
try:
config = configparser.ConfigParser()
config.read('heimdall.conf')
dbDetails = config['DATABASE']
con = psycopg2.connect(
database = dbDetails['PG_DBNAME'],user = dbDetails['PG_USER'], password = dbDetails['PG_PASS'],host = dbDetails['PG_HOST'], port = dbDetails['PG_PORT']
)
con.autocommit = True
cur = con.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS invites(invite_code text primary key, uses int, role_linked text, role_id text)')
return con
except (Exception, psycopg2.DatabaseError) as error:
print('Error occured while creating PostgreSQL Table: ', error)
return False
except Exception as err:
print("Error Connecting to PostgreSQL Server: ",err)
def fetchall(self):
try:
con = self.connect()
con.autocommit = True
cur = con.cursor()
cur.execute('SELECT * FROM invites')
row = cur.fetchone()
data = []
while row is not None:
data.append({"invite_code": row[0], "uses": row[1],"role_linked": row[2], "role_id": row[3]})
row = cur.fetchone()
con.close()
return data
except Exception as error:
print(error)
return {}
def fetchone(self, column, where=None):
try:
con = self.connect()
cur = con.cursor()
column = ','.join(column)
if(where == None):
cur.execute(f'SELECT {column} FROM invites')
else:
where_clause = f"WHERE {list(where.keys())[0]} = '{list(where.values())[0]}'"
cur.execute(f'SELECT {column} FROM invites {where_clause}')
rows = cur.fetchall()
data = {'data':[]}
for row in rows:
if(len(row)>1):
data[row[0]]=row[1]
else:
data['data'].append(row[0])
return data
except Exception as e:
print(e)
return {}
def insert(self, data):
try:
con = self.connect()
con.autocommit = True
cur = con.cursor()
cur.execute(f"INSERT INTO invites(invite_code, uses, role_linked, role_id) VALUES('{data['invite_code']}', {data['uses']}, '{data['role_linked']}', '{data['role_id']}')")
con.close()
return True
except mysql.connector.Error as err:
if err.errno == 1146:
self.createMySQLDB()
self.insert(data)
except Exception as error:
print(error)
return False
def update(self, set, where):
try:
con = self.connect()
con.autocommit = True
cur = con.cursor()
cur.execute(f"UPDATE invites SET {list(set.keys())[0]}='{list(set.values())[0]}' WHERE {list(where.keys())[0]}='{list(where.values())[0]}'")
con.close()
return True
except Exception as error:
print(error)
return False
def delete(self, where):
try:
con = self.connect()
con.autocommit = True
cur = con.cursor()
where_clause = f"WHERE {list(where.keys())[0]}='{list(where.values())[0]}'"
cur.execute(f"DELETE FROM invites {where_clause}")
return True
except Exception as e:
print(e)
return False
class JSON(Database):
def connect(self):
try:
f = open('data.json')
data = json.load(f)
return data['data']
except Exception as error:
print('Error while fetching JSON file:', error)
return False
def fetchall(self):
try:
data = self.connect()
return data
except Exception as error:
print("Error while fetching JSON file: ",error)
return False
def fetchone(self, row, where=None):
try:
data = self.connect()
rows = {'data':[]}
if where == None:
for line in data:
if(type(row)==list and len(row)>1):
rows[line[row[0]]] = line[row[1]]
else:
rows['data'].append(line[row[0]])
return rows
else:
for line in data:
if list(where.values())[0] == line[list(where.keys())[0]]:
if(type(row)==list and len(row)>1):
rows[line[row[0]]] = line[row[1]]
else:
rows['data'].append(line[row[0]])
except Exception as error:
print("Error while fetching JSON file: ",error)
return False
def insert(self, row):
try:
data = self.connect()
data.append(row)
data = {'data': data}
with open('data.json','w+') as d:
json.dump(data, d)
return True
except Exception as error:
print("Error while inserting to JSON file: ",error)
return False
def update(self, set, where):
try:
data = self.connect()
for line in data:
if line[list(where.keys())[0]] == list(where.values())[0]:
line[list(set.keys())[0]] = list(set.values())[0]
data = {'data': data}
with open('data.json','w+') as d:
json.dump(data, d)
return True
except Exception as error:
print("Error while updating JSON file: ",error)
return False
def delete(self, where=None):
try:
data = self.connect()
for i in range(len(data)):
if data[i][list(where.keys())[0]] == list(where.values())[0]:
data.pop(i)
data = {'data': data}
with open('data.json','w+') as d:
json.dump(data, d)
return True
except Exception as error:
print("Error while deleting from JSON file: ",error)
return False
class SQLite3(Database):
def connect(self):
try:
con = sqlite3.connect('invites.db')
cur = con.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS invites(invite_code text primary key, uses int, role_linked text, role_id text)')
con.commit()
return con
except Exception as e:
print('Error connecting to SQLite3 DB: ',e)
def fetchall(self):
try:
con = self.connect()
cur = con.cursor()
result = cur.execute('SELECT * FROM invites').fetchall()
data = []
for row in result:
data.append({"invite_code": row[0], "uses": row[1],"role_linked": row[2], "role_id": row[3]})
con.commit()
con.close()
return data
except Exception as error:
print(error)
return {}
def fetchone(self, column, where=None):
try:
con = self.connect()
cur = con.cursor()
column = ','.join(column)
if(where == None):
cur.execute(f'SELECT {column} FROM invites')
else:
where_clause = f'WHERE {list(where.keys())[0]} = "{list(where.values())[0]}"'
cur.execute(f'SELECT {column} FROM invites {where_clause}')
rows = cur.fetchall()
data = {'data':[]}
for row in rows:
if(len(row)>1):
data[row[0]]=row[1]
else:
data['data'].append(row[0])
return data
except Exception as e:
print(e)
return {}
def insert(self, data):
try:
con = self.connect()
cur = con.cursor()
cur.execute(f"INSERT INTO invites(invite_code, uses, role_linked, role_id) VALUES('{data['invite_code']}', {data['uses']}, '{data['role_linked']}', '{data['role_id']}')")
con.commit()
con.close()
return True
except mysql.connector.Error as err:
if err.errno == 1146:
self.createMySQLDB()
self.insert(data)
except Exception as error:
print(error)
return False
def update(self, set, where):
try:
con = self.connect()
cur = con.cursor()
cur.execute(f"UPDATE invites SET {list(set.keys())[0]}='{list(set.values())[0]}' WHERE {list(where.keys())[0]}='{list(where.values())[0]}'")
con.commit()
con.close()
return True
except Exception as error:
print(error)
return False
def delete(self, where):
try:
con = self.connect()
cur = con.cursor()
where_clause = f'WHERE {list(where.keys())[0]}="{list(where.values())[0]}"'
cur.execute(f'DELETE FROM invites {where_clause}')
con.commit()
con.close()
return True
except Exception as e:
print(e)
return False
class MongoDB(Database):
def connect(self):
try:
config = configparser.ConfigParser()
config.read('heimdall.conf')
dbDetails = config['DATABASE']
con_string = dbDetails['MONGO_URL']
client = MongoClient(con_string)
database = client['heimdall']
return database['invites']
except Exception as e:
print('Error connecting to MongoDB: ',e)
def fetchall(self):
try:
collection = self.connect()
data = []
for doc in collection.find():
data.append(doc)
return data
except Exception as error:
print(error)
return {}
def fetchone(self, column, where=None):
try:
collection = self.connect()
data = {'data':[]}
if(where == None):
for doc in collection.find({}, {key: 1 for key in column}):
if(len(column)>1):
data[doc[column[0]]] = doc[column[1]]
else:
data['data'].append(doc[column])
else:
for doc in collection.find(where, {key: 1 for key in column}):
if(len(column)>1):
data[doc[column[0]]] = doc[column[1]]
else:
data['data'].append(doc[column])
return data
except Exception as e:
print(e)
return {}
def insert(self, data):
try:
collection = self.connect()
collection.insert_one(data)
return True
except Exception as error:
print(error)
return False
def update(self, set, where):
try:
collection = self.connect()
collection.update_one(where, {'$set': set})
return True
except Exception as error:
print(error)
return False
def delete(self, where):
try:
collection = self.connect()
collection.delete_many(where)
return True
except Exception as e:
print(e)
return False