-
Notifications
You must be signed in to change notification settings - Fork 5
/
SuperHash-mysqldb.py
337 lines (244 loc) · 8.35 KB
/
SuperHash-mysqldb.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
"""DB wrapper that uses smart struct-like objects to track data changes.
original author: Jeremy Friesen
updated by: Adam Vandenberg
Database is a layer on top of MySQLdb.
A SuperHash is a struct-like object that tracks updates to the underlying data. The string representation of an SuperHash is a string of change values of the form "name=value,name=value,name=value" that can be placed into the SET clause of a SQL INSERT or UPDATE.
"""
import MySQLdb
import time
class Error(Exception): pass
class ConditionMissingError(Error): pass
class TableMissingError(Error): pass
class NoRowsFoundError(Error): pass
def esc(thing):
"Stringize and escape something for use in a SQL statement."
if thing is None:
return 'NULL'
else:
return '"%s"' % MySQLdb.escape_string(str(thing))
class Database(object):
"The database connection."
def date():
"The current date in SQL format (YYYY-MM-DD)."
return time.strftime("%Y-%m-%d", time.localtime(time.time()))
date = staticmethod(date)
def datetime():
"The current datetime in SQL format (YYYY-MM-DD HH:MM:SS)."
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
datetime = staticmethod(datetime)
def __init__(self, username, dbname, dbpass='',hostname="localhost"):
"Connect to the DB. Exceptions may be raised."
self.DB = MySQLdb.connect(host=hostname, user=username, db=dbname, passwd=dbpass)
self.debug = False
def __del__(self):
"Clean up if connected."
try:
self.DB.close()
except:
pass
# Create a superhash with exact columns
def newRow(self, table, data=None):
columns = self.loadSchema(table)
row = SuperHash(table=table, cols=[col.Field for col in columns])
if data is not None:
row._Add(data, False)
return row
def execute(self, operation, args=None):
"Send one command to the database and execute it."
if self.debug: print 'Executing '+operation
cur = self.DB.cursor()
cur.execute(operation,args)
return cur
def loadObject(self, command, args=None):
"Execute the command and return one object."
cur = self.execute(command, args)
data = self.objectFromCursor(cur)
cur.close()
return data
def loadObjects(self, command, args=None):
"Execute the command and return a list of objects."
cur = self.execute(command, args)
data = self.objectsFromCursor(cur)
cur.close()
return data
def loadSchema(self, table):
return self.loadObjects("SHOW COLUMNS FROM %s" % table)
def loadRow(self, table, id, name=None, cols=None):
"Load a DB row from a table"
if name is None: name = "id"
if cols is None: cols = "*"
row = self.loadObject(
"select %s from %s where %s=%%s" % (",".join(cols), table, name), id)
if row is not None:
row._Table = table
return row
def loadValue(self, command, args=None, default=None):
"""Load a single value from the DB.
Returns the value from the first column of the first row of the result set. If no rows were returned, returns None.
NOTE: This function returns None for no rows OR if the value is NULL.
"""
cur = self.execute(command, args)
if cur.rowcount == 0:
return default
data = cur.fetchone()
cur.close()
return data[0]
def objectFromCursor(self, cur):
"Load one object from a DB cursor."
row = cur.fetchone()
if row is None:
return None
obj = SuperHash()
for i in range(len(row)):
obj._Data[cur.description[i][0]] = row[i]
return obj
def objectsFromCursor(self, cur):
"Load all objects from a DB cursor. If there are no results an empty list is returned."
return [self.objectFromCursor(cur) for i in range(cur.rowcount)]
def storedID(self):
return self.loadValue("SELECT LAST_INSERT_ID()")
def storeObject(self, table, obj, getID=True):
"Inserts an object into the db."
setvars = obj._GetData(True)
if setvars == "": return
command = "insert into "+table+" set "+setvars
self.execute(command)
if getID: obj.id=self.storedID()
obj._Clean()
def updateObject(self, table, obj, condition):
"Updates an object in the db based on a condition."
if condition is None:
raise ConditionMissingError, "Update to table %s with no condition." %(table,)
setvars = str(obj)
if setvars == "":
return
command = "update %s set %s where %s" % (table,setvars,condition)
self.execute(command)
obj._Clean()
def updateRow(self, table, obj):
"Updates an object in the db on the ID of the row."
self.updateObject(table, obj, 'id=' + esc(obj.id))
def deleteRow(self, table, obj):
self.execute('delete from %s where id=%%s' % table, obj.id)
class SuperHash(object):
"""A struct-like object that tracks data changes.
a = SuperHash()
a.key = 'value'
This object acts like an expandable struct that tracks changes to data. The str() of a SuperHash is a string that can be used in the SET clause of a SQL INSERT or UPDATE statment.
"""
def __init__(self, table=None, cols=None):
self._Table = table
self._Columns = cols
self._Data = {}
self._Touched = {}
def _Store(self, db):
if self._Table is None: raise TableMissingError, "No table defined for this row"
db.storeObject(self._Table, self)
def _Update(self, db):
if self._Table is None: raise TableMissingError, "No table defined for this row"
db.updateRow(self._Table, self)
def _Delete(self, db):
if self._Table is None: raise TableMissingError, "No table defined for this row"
db.deleteRow(self._Table, self)
def __getattr__(self, name):
"Route database variables to OB_Data."
try:
return self.__getitem__(name)
except IndexError, error:
raise AttributeError, error
def __setattr__(self, name, value):
"Set a variable and touch it."
if name.startswith("_"):
object.__setattr__(self,name,value)
else:
try:
self.__setitem__(name,value)
except IndexError, error:
raise AttributeError, error
def __repr__(self):
"Dump the key=value data. Dirty items have a * by them."
value_strs = []
for key in self._Data:
dirty = ""
if key in self._Touched:
dirty = "*"
value_strs.append( "%s%s: %s" % (dirty, key, self._Data[key]) )
return "<SuperHash: " + ", ".join(value_strs) + ">"
def _GetData(self, includeAll=False):
"Turn this superhash into a key=value list of changed values."
if includeAll:
keys = self._Data.keys()
else:
keys = self._Touched.keys()
fields = ["%s=%s" % (key, esc(self._Data[key])) for key in keys]
return ','.join(fields)
def __str__(self):
return self._GetData(False)
def _Clean(self):
self._Touched = {}
def __getitem__(self, name):
columns = self._Columns
if columns is not None:
if not name in columns:
raise IndexError, "No column named "+name
try:
return self._Data[name]
except KeyError, attr:
if columns is not None:
return None
else:
raise IndexError, "No data for column " +name
def __setitem__(self, name, value):
if self._Columns is not None:
if not name in self._Columns:
raise IndexError, "No column named "+name
#Only dirty data if it changes
old_value = self._Data.get(name)
if (old_value != value):
self._Data[name] = value
self._Touched[name] = True
def __contains__(self, name):
if self._Columns is not None:
return name in self._Columns
else:
return name in self._Data
def _Add(self, hash, dirty=True):
"""Add values in hash to _Data.
Defaults to adding data as dirty. Pass dirty=False to insert clean data.
"""
for key in hash:
self._Data[key] = hash[key]
if dirty:
self._Touched[key] = True
class ProxyMixin(object):
def __init__(self, row):
self.__row = row
def __getattr__(self, name):
"Act as a proxy for the user db row"
return self.__row.__getattr__(name)
def __getitem__(self, name):
return self.__row.__getitem__(name)
def __setitem__(self, name, value):
return self.__row.__setitem__(name, value)
def __contains__(self, name):
return self.__row.__contains__(name)
def demo():
"A cheesy test script."
print "Creating a SuperHash..."
a = SuperHash()
# Add some clean data
a_Add({'beef':'steak', 'chicken':'nuggets'}, False)
# Dirty up some data
a.beef = "Wellington"
a.pork = "chops"
print "Repr: ",repr(a)
print "Str: ",str(a)
print
print "Adding a hash..."
a._Add({'eggs': 'benedict', 'orange': 'juice'}, False)
a._Add({'orange': 'peels', 'grapefruit': 'wedges'})
print "Repr: ",repr(a)
print "Str: ",str(a)
print
if __name__=="__main__":
demo()