-
Notifications
You must be signed in to change notification settings - Fork 10
/
db.py
310 lines (282 loc) · 11.4 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
import psycopg2
import ircHelpers
import yaml
class DB:
# info for all tables. # increment version number when updating create (look at self.__on_upgrade() too)
tables = {
## table | version, schema
'tables' : (1,
"table_name text PRIMARY KEY, "+
"current_version integer NOT NULL"),
'mail' : (1,
"sender text NOT NULL, "+
"recipient text NOT NULL, "+
"message text NOT NULL, "+
"id text NOT NULL"),
'projects' : (1,
"name text NOT NULL, "+
"language text NULL, "+
"link text NULL, "+
"description text NULL, "+
"id text NOT NULL"),
'users' : (1,
"_id integer PRIMARY KEY DEFAULT nextval('serial'), "+
"nick text NOT NULL, "+
"userlevel integer NOT NULL DEFAULT 0, "+
"last_online integer NOT NULL"),
'logs' : (1,
"_id integer PRIMARY KEY DEFAULT nextval('serial'), "+
"time type text NOT NULL, "+
"log text NOT NULL")
}
# unmanaged_tables are left alone by the automatic table handling - don't get created, updated etc
unmanaged_tables = ('logs', 'users', 'tables')
# future table ideas:
# user: possibly include timezone settings to localise timestamps on logs, mail etc for each user (maybe with a '!!me' command group)
def __init__(self):
# test that all (managed) tables exist and are at correct version (version check not implemented yet)
self.__ensure_all_tables_correct()
def db_connect(self):
with open("irc.yaml", 'r') as settings_file:
conf = yaml.load(settings_file)
try:
conn = psycopg2.connect(
database = conf['database']['name'],
user = conf['database']['user'],
password = conf['database']['pass'],
host = conf['database']['host'],
port = conf['database']['port'])
return conn
except psycopg2.Error as e:
print("!! Error connecting to db")
print(e)
return None
def db_add_table(self,table_name,table_info):
# table_info should follow proper sql format.
# i.e: db_add_table("test", "id PRIMARY_KEY, name varchar(20, sample_data text)")
print(".. Creating table: %s...\n Schema: %s" % (table_name, table_info))
try:
if not self.db_check_table(table_name):
conn = self.db_connect()
cur = conn.cursor()
SQL = "CREATE TABLE IF NOT EXISTS %s (%s);" % (table_name,table_info)
cur.execute(SQL)
conn.commit()
return True
else:
print("!! Error creating table %s. Already exists" % table_name)
return False
except psycopg2.Error as e:
print("!! Error creating new table: %s" % table_name)
print(e)
return False
finally:
try:
conn.close()
except Exception:
pass
def db_drop_table(self,table_name):
try:
if self.db_check_table(table_name):
conn = self.db_connect()
cur = conn.cursor()
SQL = "DROP TABLE IF EXISTS %s" % table_name
cur.execute(SQL)
conn.commit()
return True
else:
ircHelpers.sayInChannel("There is no table: %s" % table_name)
return False
except psycopg2.Error as e:
print("!! Error dropping table: %s" % table_name)
print(e)
return False
finally:
try:
conn.close()
except Exception:
pass
def db_add_data(self,table_name,data):
try:
if self.db_check_table(table_name):
conn = self.db_connect()
cur = conn.cursor()
table_columns = ''
column_data =''
for key in data.keys():
table_columns = table_columns + key + ", "
column_data = column_data + "'" + data[key] + "', "
table_columns = table_columns[:-2]
column_data = column_data[:-2]
SQL = "INSERT INTO %s (%s) VALUES(%s);" % (table_name,table_columns,column_data)
cur.execute(SQL)
conn.commit()
return True
else:
ircHelpers.sayInChannel("There is no table: %s" % table_name)
return False
except psycopg2.Error as e:
print("!! Error adding data to table: %s" % table_name)
print(e)
return False
finally:
try:
conn.close()
except Exception:
pass
def db_get_data(self,table_name,condition_column_name,condition_value,):
try:
if self.db_check_table(table_name):
conn = self.db_connect()
cur = conn.cursor()
SQL = "SELECT * FROM %s WHERE %s = '%s'" % (table_name,condition_column_name,condition_value)
cur.execute(SQL)
response = cur.fetchall()
return response
else:
return None
except psycopg2.Error as e:
print("!! Error retrieving data from table: %s" % table_name)
print(e)
return None
finally:
try:
conn.close()
except Exception:
pass
def db_get_all_data(self,table_name):
try:
if self.db_check_table(table_name):
conn = self.db_connect()
cur = conn.cursor()
SQL = "SELECT * FROM %s" % (table_name)
cur.execute(SQL)
response = cur.fetchall()
return response
else:
return None
except psycopg2.Error as e:
print("!! Error retrieving data from table: %s" % table_name)
print(e)
return None
finally:
try:
conn.close()
except Exception:
pass
def db_delete_data(self,table_name,condition_column_name,condition_value):
try:
if self.db_check_table(table_name):
conn = self.db_connect()
cur = conn.cursor()
SQL = "DELETE FROM %s WHERE %s = '%s'" % (table_name,condition_column_name,condition_value)
cur.execute(SQL)
conn.commit()
return True
else:
ircHelpers.sayInChannel("There is no table: %s" % table_name)
return False
except psycopg2.Error as e:
print("!! Error deleting data from table: %s" % table_name)
print(e)
return False
finally:
try:
conn.close()
except Exception:
pass
def db_update_data(self,table_name,column_name,changed_value,condition_column_name,condition_value,):
try:
if self.db_check_table(table_name):
conn = self.db_connect()
cur = conn.cursor()
SQL = "UPDATE "+table_name+" SET "+column_name+" = %s WHERE "+condition_column_name+" = "+condition_value
cur.execute(SQL, (changed_value))
conn.commit()
return True
else:
ircHelpers.sayInChannel("There is no table: %s" % table_name)
return False
except psycopg2.Error as e:
print("!! Error updating data in table: %s" % table_name)
print(e)
return False
finally:
try:
conn.close()
except Exception:
pass
def db_check_table(self,table_name):
try:
conn = self.db_connect()
cur = conn.cursor()
SQL = "SELECT EXISTS(SELECT * FROM information_schema.tables WHERE table_name=%s)"
data = (table_name, )
cur.execute(SQL, data)
response = cur.fetchone()[0]
if not response:
print("!! DB Table not exists: %s" % table_name)
return response
except psycopg2.Error as e:
print("!! Error checking table exists: %s [ironic, right?]" % table_name)
print(e)
return False ##ASK Really want to return False on fail here?? Table may actually exist.
finally:
try:
conn.close()
except Exception:
pass
def __ensure_all_tables_correct(self):
all_tables = DB.tables.keys()
all_successful = True
print(".. Checking all tables...")
for table in all_tables:
if table in DB.unmanaged_tables:
continue
if self.__ensure_table_correct(table):
print(".. Table found: %s" % table)
else:
print("!! Table not found: %s" % table)
if self.__recreate_table(table):
print(".. Created table: %s" % table)
else:
print("!! Failed to create table: %s" % table)
all_successful = False
return all_successful
def __ensure_table_correct(self, table_name):
# TODO Test old/new version numbers and trigger __on_upgrade, __recreate etc etc
# For now we'll just test if table exists
return self.db_check_table(table_name)
def __recreate_table(self, table_name):
go_for_new = False
if self.db_check_table(table_name):
if self.db_drop_table(table_name):
go_for_new = True
else:
go_for_new = True
if go_for_new:
if self.db_add_table(table_name, self.tables[table_name][1]):
return True
return False
def __on_upgrade(self, table_name, new_version, old_version=0):
# Can eventually handle upgrades to tables without losing data
# by making use of the version numbers
# For now just destroy and recreate the tables
# Skipping the projects table to retain info
if table_name == 'mail':
return self.__recreate_table('mail')
elif table_name == 'projects':
if self.db_check_table('projects'):
print(".. Attempt to upgrade/recreate Projects table. Ignored to preserve info until upgrade possible")
return True # cheaty
else:
return self.__recreate_table('projects')
elif table_name == 'users':
return self.__recreate_table('users')
elif table_name == 'logs':
return self.__recreate_table('logs')
else:
print("Unsupported table: %s. Add to db.tables and db.__on_upgrade to deploy")
return False
if __name__ == "__main__":
pass