-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsqlmapper.py
429 lines (383 loc) · 17.9 KB
/
sqlmapper.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# sqlmapper.py
# PythonSQLMapper
#
# Copyright 2013-2023 Kenji Nishishiro. All rights reserved.
# Written by Kenji Nishishiro <marvel@programmershigh.org>.
#
import re
class MappingError(Exception):
pass
class DriverWarning(MappingError):
pass
class DriverError(MappingError):
pass
class DriverInterfaceError(DriverError):
pass
class DriverDatabaseError(DriverError):
pass
class DriverDataError(DriverDatabaseError):
pass
class DriverOperationalError(DriverDatabaseError):
pass
class DriverIntegrityError(DriverDatabaseError):
pass
class DriverInternalError(DriverDatabaseError):
pass
class DriverProgrammingError(DriverDatabaseError):
pass
class DriverNotSupportedError(DriverDatabaseError):
pass
class Result(object):
pass
class Mapper(object):
def __init__(self, driver, **params):
self.connection = None
try:
self.driver = driver
if driver.__name__ == "sqlite3":
self.__cursor_params = {}
self.__buffered_cursor_params = self.__cursor_params
self.__place_holder = "?"
elif driver.__name__ == "mysql.connector":
self.__cursor_params = {"dictionary": True}
self.__buffered_cursor_params = {"dictionary": True, "buffered": True}
self.__place_holder = "%s"
elif driver.__name__ == "MySQLdb":
import MySQLdb.cursors
self.__cursor_params = {"cursorclass": MySQLdb.cursors.SSDictCursor}
self.__buffered_cursor_params = {"cursorclass": MySQLdb.cursors.DictCursor}
self.__place_holder = "%s"
elif driver.__name__ == "pymysql":
import pymysql.cursors
self.__cursor_params = {"cursor": pymysql.cursors.SSDictCursor}
self.__buffered_cursor_params = {"cursor": pymysql.cursors.DictCursor}
self.__place_holder = "%s"
elif driver.__name__ == "oursql":
self.__cursor_params = {"cursor_class": driver.DictCursor}
self.__buffered_cursor_params = self.__cursor_params
self.__place_holder = "?"
elif driver.__name__ == "psycopg2":
import psycopg2.extras
self.__cursor_params = {"cursor_factory": psycopg2.extras.RealDictCursor}
self.__buffered_cursor_params = self.__cursor_params
self.__place_holder = "%s"
else:
raise MappingError("Unsupported driver.")
self.connection = self.driver.connect(**params)
if driver.__name__ == "sqlite3":
self.connection.row_factory = driver.Row
except self.driver.NotSupportedError as error:
raise DriverNotSupportedError(*error.args) from error
except self.driver.ProgrammingError as error:
raise DriverProgrammingError(*error.args) from error
except self.driver.InternalError as error:
raise DriverInternalError(*error.args) from error
except self.driver.IntegrityError as error:
raise DriverIntegrityError(*error.args) from error
except self.driver.OperationalError as error:
raise DriverOperationalError(*error.args) from error
except self.driver.DataError as error:
raise DriverDataError(*error.args) from error
except self.driver.DatabaseError as error:
raise DriverDatabaseError(*error.args) from error
except self.driver.InterfaceError as error:
raise DriverInterfaceError(*error.args) from error
except self.driver.Error as error:
raise DriverError(*error.args) from error
except self.driver.Warning as error:
raise DriverWarning(*error.args) from error
def close(self):
try:
if self.connection is not None:
self.connection.close()
self.connection = None
except self.driver.NotSupportedError as error:
raise DriverNotSupportedError(*error.args) from error
except self.driver.ProgrammingError as error:
raise DriverProgrammingError(*error.args) from error
except self.driver.InternalError as error:
raise DriverInternalError(*error.args) from error
except self.driver.IntegrityError as error:
raise DriverIntegrityError(*error.args) from error
except self.driver.OperationalError as error:
raise DriverOperationalError(*error.args) from error
except self.driver.DataError as error:
raise DriverDataError(*error.args) from error
except self.driver.DatabaseError as error:
raise DriverDatabaseError(*error.args) from error
except self.driver.InterfaceError as error:
raise DriverInterfaceError(*error.args) from error
except self.driver.Error as error:
raise DriverError(*error.args) from error
except self.driver.Warning as error:
raise DriverWarning(*error.args) from error
def __del__(self):
self.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def select_one(self, sql, parameter=None, result_type=None):
try:
cursor = self.connection.cursor(**self.__cursor_params)
try:
cursor.execute(*self.__map_parameter(sql, parameter))
rows = cursor.fetchmany(2)
if len(rows) == 0:
return None
elif len(rows) == 1:
return self.__create_result(row=rows[0], result_type=result_type)
else:
raise MappingError("Multiple result was obtained.")
finally:
cursor.close()
except self.driver.NotSupportedError as error:
raise DriverNotSupportedError(*error.args) from error
except self.driver.ProgrammingError as error:
raise DriverProgrammingError(*error.args) from error
except self.driver.InternalError as error:
raise DriverInternalError(*error.args) from error
except self.driver.IntegrityError as error:
raise DriverIntegrityError(*error.args) from error
except self.driver.OperationalError as error:
raise DriverOperationalError(*error.args) from error
except self.driver.DataError as error:
raise DriverDataError(*error.args) from error
except self.driver.DatabaseError as error:
raise DriverDatabaseError(*error.args) from error
except self.driver.InterfaceError as error:
raise DriverInterfaceError(*error.args) from error
except self.driver.Error as error:
raise DriverError(*error.args) from error
except self.driver.Warning as error:
raise DriverWarning(*error.args) from error
def select_all(self, sql, parameter=None, result_type=None, array_size=1, buffered=True):
try:
if buffered:
cursor = self.connection.cursor(**self.__buffered_cursor_params)
else:
cursor = self.connection.cursor(**self.__cursor_params)
try:
cursor.execute(*self.__map_parameter(sql, parameter))
rows = cursor.fetchmany(array_size)
while rows:
for row in rows:
yield self.__create_result(row=row, result_type=result_type)
rows = cursor.fetchmany(array_size)
finally:
cursor.close()
except self.driver.NotSupportedError as error:
raise DriverNotSupportedError(*error.args) from error
except self.driver.ProgrammingError as error:
raise DriverProgrammingError(*error.args) from error
except self.driver.InternalError as error:
raise DriverInternalError(*error.args) from error
except self.driver.IntegrityError as error:
raise DriverIntegrityError(*error.args) from error
except self.driver.OperationalError as error:
raise DriverOperationalError(*error.args) from error
except self.driver.DataError as error:
raise DriverDataError(*error.args) from error
except self.driver.DatabaseError as error:
raise DriverDatabaseError(*error.args) from error
except self.driver.InterfaceError as error:
raise DriverInterfaceError(*error.args) from error
except self.driver.Error as error:
raise DriverError(*error.args) from error
except self.driver.Warning as error:
raise DriverWarning(*error.args) from error
def insert(self, sql, parameter=None):
try:
cursor = self.connection.cursor(**self.__cursor_params)
try:
cursor.execute(*self.__map_parameter(sql, parameter))
return cursor.lastrowid
finally:
cursor.close()
except self.driver.NotSupportedError as error:
raise DriverNotSupportedError(*error.args) from error
except self.driver.ProgrammingError as error:
raise DriverProgrammingError(*error.args) from error
except self.driver.InternalError as error:
raise DriverInternalError(*error.args) from error
except self.driver.IntegrityError as error:
raise DriverIntegrityError(*error.args) from error
except self.driver.OperationalError as error:
raise DriverOperationalError(*error.args) from error
except self.driver.DataError as error:
raise DriverDataError(*error.args) from error
except self.driver.DatabaseError as error:
raise DriverDatabaseError(*error.args) from error
except self.driver.InterfaceError as error:
raise DriverInterfaceError(*error.args) from error
except self.driver.Error as error:
raise DriverError(*error.args) from error
except self.driver.Warning as error:
raise DriverWarning(*error.args) from error
def update(self, sql, parameter=None):
try:
cursor = self.connection.cursor(**self.__cursor_params)
try:
cursor.execute(*self.__map_parameter(sql, parameter))
return cursor.rowcount
finally:
cursor.close()
except self.driver.NotSupportedError as error:
raise DriverNotSupportedError(*error.args) from error
except self.driver.ProgrammingError as error:
raise DriverProgrammingError(*error.args) from error
except self.driver.InternalError as error:
raise DriverInternalError(*error.args) from error
except self.driver.IntegrityError as error:
raise DriverIntegrityError(*error.args) from error
except self.driver.OperationalError as error:
raise DriverOperationalError(*error.args) from error
except self.driver.DataError as error:
raise DriverDataError(*error.args) from error
except self.driver.DatabaseError as error:
raise DriverDatabaseError(*error.args) from error
except self.driver.InterfaceError as error:
raise DriverInterfaceError(*error.args) from error
except self.driver.Error as error:
raise DriverError(*error.args) from error
except self.driver.Warning as error:
raise DriverWarning(*error.args) from error
def delete(self, sql, parameter=None):
try:
cursor = self.connection.cursor(**self.__cursor_params)
try:
cursor.execute(*self.__map_parameter(sql, parameter))
return cursor.rowcount
finally:
cursor.close()
except self.driver.NotSupportedError as error:
raise DriverNotSupportedError(*error.args) from error
except self.driver.ProgrammingError as error:
raise DriverProgrammingError(*error.args) from error
except self.driver.InternalError as error:
raise DriverInternalError(*error.args) from error
except self.driver.IntegrityError as error:
raise DriverIntegrityError(*error.args) from error
except self.driver.OperationalError as error:
raise DriverOperationalError(*error.args) from error
except self.driver.DataError as error:
raise DriverDataError(*error.args) from error
except self.driver.DatabaseError as error:
raise DriverDatabaseError(*error.args) from error
except self.driver.InterfaceError as error:
raise DriverInterfaceError(*error.args) from error
except self.driver.Error as error:
raise DriverError(*error.args) from error
except self.driver.Warning as error:
raise DriverWarning(*error.args) from error
def execute(self, sql, parameter=None):
try:
cursor = self.connection.cursor(**self.__cursor_params)
try:
cursor.execute(*self.__map_parameter(sql, parameter))
finally:
cursor.close()
except self.driver.NotSupportedError as error:
raise DriverNotSupportedError(*error.args) from error
except self.driver.ProgrammingError as error:
raise DriverProgrammingError(*error.args) from error
except self.driver.InternalError as error:
raise DriverInternalError(*error.args) from error
except self.driver.IntegrityError as error:
raise DriverIntegrityError(*error.args) from error
except self.driver.OperationalError as error:
raise DriverOperationalError(*error.args) from error
except self.driver.DataError as error:
raise DriverDataError(*error.args) from error
except self.driver.DatabaseError as error:
raise DriverDatabaseError(*error.args) from error
except self.driver.InterfaceError as error:
raise DriverInterfaceError(*error.args) from error
except self.driver.Error as error:
raise DriverError(*error.args) from error
except self.driver.Warning as error:
raise DriverWarning(*error.args) from error
def commit(self):
try:
self.connection.commit()
except self.driver.NotSupportedError as error:
raise DriverNotSupportedError(*error.args) from error
except self.driver.ProgrammingError as error:
raise DriverProgrammingError(*error.args) from error
except self.driver.InternalError as error:
raise DriverInternalError(*error.args) from error
except self.driver.IntegrityError as error:
raise DriverIntegrityError(*error.args) from error
except self.driver.OperationalError as error:
raise DriverOperationalError(*error.args) from error
except self.driver.DataError as error:
raise DriverDataError(*error.args) from error
except self.driver.DatabaseError as error:
raise DriverDatabaseError(*error.args) from error
except self.driver.InterfaceError as error:
raise DriverInterfaceError(*error.args) from error
except self.driver.Error as error:
raise DriverError(*error.args) from error
except self.driver.Warning as error:
raise DriverWarning(*error.args) from error
def rollback(self):
try:
self.connection.rollback()
except self.driver.NotSupportedError as error:
raise DriverNotSupportedError(*error.args) from error
except self.driver.ProgrammingError as error:
raise DriverProgrammingError(*error.args) from error
except self.driver.InternalError as error:
raise DriverInternalError(*error.args) from error
except self.driver.IntegrityError as error:
raise DriverIntegrityError(*error.args) from error
except self.driver.OperationalError as error:
raise DriverOperationalError(*error.args) from error
except self.driver.DataError as error:
raise DriverDataError(*error.args) from error
except self.driver.DatabaseError as error:
raise DriverDatabaseError(*error.args) from error
except self.driver.InterfaceError as error:
raise DriverInterfaceError(*error.args) from error
except self.driver.Error as error:
raise DriverError(*error.args) from error
except self.driver.Warning as error:
raise DriverWarning(*error.args) from error
def __map_parameter(self, sql, parameter):
represented_sql = ""
parameters = ()
start = 0
for match in re.finditer(":[a-zA-Z_][a-zA-Z0-9_]+", sql):
# TODO: Support paramstyle
represented_sql += sql[start : match.start()] + self.__place_holder
start = match.end()
parameters += (self.__get_variable(parameter, sql[match.start() + 1 : match.end()]),)
represented_sql += sql[start:]
return represented_sql, parameters
@staticmethod
def __get_variable(parameter, name):
try:
if isinstance(parameter, dict):
return parameter[name]
else:
return getattr(parameter, name)
except (KeyError, AttributeError):
raise MappingError("Bind variable '{0}' not found in '{1}'.".format(name, parameter))
@staticmethod
def __create_result(row, result_type):
if result_type is None:
result = Result()
for name in row:
setattr(result, name, row[name])
return result
else:
result = result_type()
for name in row:
if hasattr(result, name):
setattr(result, name, row[name])
else:
raise MappingError("Attribute '{0}' not found in '{1}'.".format(name, result_type))
return result