-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqlmapper.py
More file actions
336 lines (282 loc) · 10.8 KB
/
sqlmapper.py
File metadata and controls
336 lines (282 loc) · 10.8 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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# sqlmapper.py
# PythonSQLMapper
#
# Copyright 2013-2026 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.driver = driver
self.connection = None
if self.driver.__name__ == "sqlite3":
self.__cursor_params = {}
self.__buffered_cursor_params = self.__cursor_params
self.__place_holder = "?"
elif self.driver.__name__ == "mysql.connector":
self.__cursor_params = {"dictionary": True}
self.__buffered_cursor_params = {"dictionary": True, "buffered": True}
self.__place_holder = "%s"
elif self.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 self.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 self.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(
f"Unsupported driver '{self.driver.__name__}'. Supported drivers: sqlite3, mysql.connector, "
"MySQLdb, pymysql, psycopg2."
)
try:
self.connection = self.driver.connect(**params)
except Exception as error:
mapped = self.__map_driver_error(error)
if mapped is not None:
raise mapped from error
else:
raise
if self.driver.__name__ == "sqlite3":
self.connection.row_factory = self.__sqlite3_dict_row_factory
def close(self):
try:
if self.connection is not None:
self.connection.close()
self.connection = None
except Exception as error:
mapped = self.__map_driver_error(error)
if mapped is not None:
raise mapped from error
else:
raise
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("Expected exactly one row, but multiple rows were returned.")
finally:
cursor.close()
except Exception as error:
mapped = self.__map_driver_error(error)
if mapped is not None:
raise mapped from error
else:
raise
returning_one = select_one
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 Exception as error:
mapped = self.__map_driver_error(error)
if mapped is not None:
raise mapped from error
else:
raise
returning_all = select_all
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 Exception as error:
mapped = self.__map_driver_error(error)
if mapped is not None:
raise mapped from error
else:
raise
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 Exception as error:
mapped = self.__map_driver_error(error)
if mapped is not None:
raise mapped from error
else:
raise
delete = update
def upsert(self, sql, parameter=None):
try:
cursor = self.connection.cursor(**self.__cursor_params)
try:
cursor.execute(*self.__map_parameter(sql, parameter))
return cursor.rowcount, cursor.lastrowid
finally:
cursor.close()
except Exception as error:
mapped = self.__map_driver_error(error)
if mapped is not None:
raise mapped from error
else:
raise
ignore = upsert
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 Exception as error:
mapped = self.__map_driver_error(error)
if mapped is not None:
raise mapped from error
else:
raise
def commit(self):
try:
self.connection.commit()
except Exception as error:
mapped = self.__map_driver_error(error)
if mapped is not None:
raise mapped from error
else:
raise
def rollback(self):
try:
self.connection.rollback()
except Exception as error:
mapped = self.__map_driver_error(error)
if mapped is not None:
raise mapped from error
else:
raise
def __map_parameter(self, sql, parameter):
represented_sql = ""
parameters = ()
start = 0
for match in re.finditer("(?<!:):[a-zA-Z_][a-zA-Z0-9_]*", sql):
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
def __map_driver_error(self, error):
if isinstance(error, self.driver.NotSupportedError):
return DriverNotSupportedError(*error.args)
elif isinstance(error, self.driver.ProgrammingError):
return DriverProgrammingError(*error.args)
elif isinstance(error, self.driver.InternalError):
return DriverInternalError(*error.args)
elif isinstance(error, self.driver.IntegrityError):
return DriverIntegrityError(*error.args)
elif isinstance(error, self.driver.OperationalError):
return DriverOperationalError(*error.args)
elif isinstance(error, self.driver.DataError):
return DriverDataError(*error.args)
elif isinstance(error, self.driver.DatabaseError):
return DriverDatabaseError(*error.args)
elif isinstance(error, self.driver.InterfaceError):
return DriverInterfaceError(*error.args)
elif isinstance(error, self.driver.Error):
return DriverError(*error.args)
elif isinstance(error, self.driver.Warning):
return DriverWarning(*error.args)
else:
return None
@staticmethod
def __sqlite3_dict_row_factory(cursor, row):
fields = [column[0] for column in cursor.description]
return {key: value for key, value in zip(fields, row)}
@staticmethod
def __get_variable(parameter, name):
if isinstance(parameter, dict):
try:
return parameter[name]
except KeyError:
raise MappingError(
f"Bind variable '{name}' was not found in dict parameter. Available keys: {sorted(parameter.keys())}"
)
else:
try:
return getattr(parameter, name)
except AttributeError:
raise MappingError(
f"Bind variable '{name}' was not found in parameter object of type '{type(parameter).__name__}'."
)
@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:
try:
result = result_type()
except TypeError:
raise MappingError(f"Result type '{result_type}' must be instantiable without arguments.")
for name in row:
if hasattr(result, name):
setattr(result, name, row[name])
else:
raise MappingError(f"Attribute '{name}' was not found in result_type '{result_type.__name__}'.")
return result