-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdbhandler.py
More file actions
executable file
·387 lines (320 loc) · 15.4 KB
/
Copy pathdbhandler.py
File metadata and controls
executable file
·387 lines (320 loc) · 15.4 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
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
"""
LEFT OFF:
Setting up the config file dbvars.cfg to set the self.columns[table] var
"""
from checklist import checklist
from inspect import getmembers
from inspect import stack
from logger import check_logger
from logger import create_logger
# from functions import *
import custom_errors
import ConfigParser
import MySQLdb
import re
import sys
import time
class db(object):
def __init__(self,
host = None,
database = None,
port = 3306,
user = None,
password = None,
log = None,
):
# try:
# Check if logger passed, else create new one
self.log = check_logger(log, self)
# Set error handler
self.error = custom_errors.error(self)
# Sets database parameters from dbvars.cfg
self._set_db_vars()
# Check for overriding vars passed into __init__
if host is not None: self.dbvars['host'] = str(host)
if database is not None: self.dbvars['database'] = str(database)
if port is not None: self.dbvars['port'] = str(port)
if user is not None: self.dbvars['user'] = str(user)
if password is not None: self.dbvars['password'] = str(password)
# Actually create the DB connection and cursor
self._set_db()
self.values = {}
self.log.info("Done.")
# except Exception, e:
# self.lasterr = error(self, e, getmembers(self), stack()
def _checklistlengths(self, columns, values):
if ((checklist(columns)) and (checklist(values))):
if (len(columns) != len(values)):
e = "".join(["'dbhandler.checklistlengths': The number of items ",
"in 'columns' and 'values' ",
"do not appear to match. ",
"If you need to insert a blank value, use ''.",
"Skipping."])
self.log.error(e)
self.log.error("".join(["columns: (",str(len(columns)),")",
str(columns)]))
self.log.error("".join(["values: (",str(len(values)),")",
str(columns)]))
return False
else: return True
else:
e = "".join(["'dbhandler.checklistlengths': The parameters ",
"'columns' and 'values' ",
"do not appear to be lists. ",
"Each of these must be passed ",
"as a list of strings."])
self.log.error(e)
self.log.error("".join(["columns: (",
str(len(columns)),
")",
str(columns)]))
self.log.error("".join(["values: (",
str(len(values)),
")",
str(values)]))
return False
def _set_db(self):
self.log.info("Starting MySQL database connection ...")
self.log.debug("Creating connection...")
self.conn=MySQLdb.connect(host = self.dbvars['host'],
db = self.dbvars['database'],
port = int(self.dbvars['port']),
user = self.dbvars['user'],
passwd = self.dbvars['password']
)
self.log.debug("Done.")
self.log.debug("Verifying connection...")
if not self._verify_connection():
e = ('Fatal: DBStartFailure')
raise Exception(e)
self.log.debug("Done.")
self.log.debug("Creating cursor...")
self.cursor = self.conn.cursor()
self.log.debug("Done.")
self.tables = []
self.cursor.execute("""show tables;""")
for row in self.cursor:
self.tables.append(row[0])
self.log.debug("Done.")
def _set_db_vars(self, filename = "../etc/dbvars.cfg"):
"""
_set_db_vars([filename])
DESCRIPTION:
Uses ConfigParser to set the column names for each table into
variable self.columns[<table>]
filename can be set for non-default configuration file name
default = dbvars.cfg
dbvars.cfg format
[tablename]
column = 'ColumnsName1'
column = 'ColumnsName2'
NOTE: _set_db_vars should only be run ONCE in __init__
"""
self.log.debug("Loading DB variables...")
try:
self.columns = {}
self.dbvars = {}
config = ConfigParser.ConfigParser()
self.log.debug("".join(["Reading: ", str(filename)]))
config.read(filename)
for section in config.sections():
# Check for specific section, otherwise assume table
if (section == 'database'):
options = config.options(section)
for option in options:
self.dbvars[option]= str(config.get(section, option))
continue
try:
# Check if key "section" (for table) already exists
if self.columns[section]:
e = "".join([
"Table '", section, "' has already been set.",
"Redundant section in configuration file.",
"Skipping. Please check dbvars.cfg"
])
self.log.error(e)
# "Table" key doesn't exist, create it as a list
except (AttributeError, KeyError, IndexError):
self.columns[section] = []
# Start loading list with the sections values
options = config.options(section)
for option in options:
self.columns[section].append(str(config.get(section, option)))
return True
except Exception, e:
raise
self.log.debug("".join(['dbhandler._set_db_varsDone: ', e]))
return False
def _cleanMysqlInsertString(self, _list, _quotes = False):
"""
Takes a list of strings, and formats then into a single string
which meets format for a MySQL insert statement
"""
if checklist(_list): # If is a list
result = "(" # Start result to be returned
for _item in _list:
# Strip carrage returns from _item
_item = str(_item)
_item = "".join(c for c in _item if c not in "\n\r")
# If a number, strip spaces
try:
if ((int(_item)) or (float(_item))):
_item = "".join(c for c in _item if not re.match("\s", c))
except ValueError: # Fails if _item has string chars
pass
# String escape
_item = _item.encode("string_escape")
# Add quotes if needed
if _quotes:
_item = _item.center(len(_item)+2, "'")
# Add item to the final return
result = "".join([result, _item, ","])
result = result[0:(len(result)-1)] # Remove last comma
result = "".join([result, ")"]) # Add last paren
return result
# Raise error if _list is not a list
else:
e = "".join(["'dbhandler._cleanMysqlInsertString' ",
"parameter is not a list."])
raise TypeError(e)
def _verify_connection(self):
# try:
self.log.debug("".join(['Checking DB connection to database: ',
str(self.dbvars['database'])]))
self.conn.query("""show tables;""")
test = self.conn.use_result()
test = test.fetch_row()
self.log.debug("Query result: " + str(test))
return True
# except Exception, e:
# e = "".join(['DBPassThroughException:', str(e)])
# self.lasterr = error(self, e, getmembers(self), stack())
# return False
def writeRowsBuffer(self, table):
"""
writeRowsBuffer(table)
DESCRIPTION:
Forms and writes an SQL statement to place data into "table"
The columns for the table are stored in non-volatile parameter
self.columns[<table>]. This is loaded at __init__
The values for the row are stored in dynamic variable
self.values[<table>]. These are created dynamically as script runs
by the method loadRowsBuffer(table, values)..
"""
try:
# Assemble write query
# Check params
_columns = self._cleanMysqlInsertString(self.columns[table])
_values = ""
try:
if len(self.values[table]) < 1:
self.log.info("self.values buffer is empty.")
return #End method execution
except (AttributeError, KeyError, ValueError):
self.log.info("self.values buffer is empty.")
return #End method execution
# Parse the values and add them to an SQL statement string
for _valuelist in self.values[table]:
_valuestring = self._cleanMysqlInsertString(
_valuelist, _quotes = True)
_values = "".join([_values,",", _valuestring])
_values = _values[1:] # Pop leading comma off
_sql = "".join(["INSERT INTO ", str(table), " ",
_columns, " ", "VALUES ", _values,
';'])
self.log.debug("Attempting insert with:")
self.log.debug(_sql)
# Only turn on for deep debugging
# self.log.debug(_sql)
try:
with self.conn:
cur = self.conn.cursor()
cur.execute(_sql)
self.log.debug("Successful.")
return True
except Exception, e:
self.log.debug("".join(["Failed with", str(e)]))
if (("duplicate" in str(e).lower()) and overwrite):
self.log.error("".join(["Duplicate entry(s) found. ",
"Overwrite is disabled in this script. ",
"Continuing without writing."]))
# self.log.debug("Overwrite true, attempting update...")
# where1 = str(columns[0])
# where2 = str(values[0])
# if self.updateRow(
# columns, values, table,
# where = "".join([where1,"=",where2]),
# prikey = where1
# ):
# self.log.debug("Successful.")
# return True
# else:
# self.log.debug("Failed.")
return False
else:
# A method for hanlding duplicate overwrites
# needs to be created
raise
except Exception, e:
e = "".join(["PassThroughException: Failed attempting to modify ",
"database row: ",
str(e)])
self.lasterr = self.error.handle(e, getmembers(self), stack())
def loadRowsBuffer(self, table = None, values = None):
"""
loadRowsBuffer(table, values)
DESCRIPTION:
Creates a list of lists "self.values[table]" as a buffer.
Each list within self.values[table] is a row of data saved for
"table".
When 'table' is sent to self.writeRowsBuffer(table), each list
found within self.values[table] is written as a row to 'table'.
"""
#### ENABLE BELOW FOR CODING DEBUG ###
# Check that keys for table have been set
# try:
# self.log.debug("".join(["Attempting loadRowsBuffer with '",
# str(table), "with:"]))
# self.log.debug("".join(["Values: (",
# str(len(values)), ")", str(values)]))
#
# except (AttributeError, KeyError):
# e = "".join(["FatalScriptError: dbahndler.write: ",
# "Table '", str(table), "' is not in self.columns.",
# "Variables for dbahndler.columns['",
# str(table), "' may not have been set." ])
# self.lasterr = self.error.handle(e,inspect.getmembers(self),inspect.stack())
#### ENABLE ABOVE BELOW FOR CODING DEBUG ###
# Check that values passed is a list that contains at least one element
try:
if not checklist(values): raise TypeError
values[0] # Errors if list is empty
except (AttributeError, TypeError, IndexError):
e = "".join(["FatalScriptError: dbahndler.write: ",
"Variable 'values' passed does not appear to be a ",
"valid list type or is of zero length. ."
])
try:
# Check if key "table" already exists
self.values[table]
# "Table" key doesn't exist, create it as a list
except (AttributeError, KeyError, IndexError):
self.values[table] = []
# Ensure the columns and values are lists of same length
# NOTE: Checking PASSED values not self.values[table]
if self._checklistlengths(self.columns[table], values):
# If no error, append self.values[table]
# NOTE: This creates a list of list, don't uuse
# self.values[table] = values
# self.values[table] will end up as a list of lists, with
# each list being a row to be added
self.values[table].append(values)
else:
self.log.error("".join(["The length of the value list ",
"does not appear to match the columns. ",
"Skipping this value set."]))
self.log.error("".join([str(values)]))
if __name__ == "__main__":
d = db(
log = None,
)