- Notifications
You must be signed in to change notification settings - Fork 442
/
Copy pathcursors.py
500 lines (405 loc) · 15.5 KB
/
cursors.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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
"""MySQLdb Cursors
This module implements Cursors of various types for MySQLdb. By
default, MySQLdb uses the Cursor class.
"""
importre
from ._exceptionsimportProgrammingError
#: Regular expression for ``Cursor.executemany```.
#: executemany only supports simple bulk insert.
#: You can use it to load large dataset.
RE_INSERT_VALUES=re.compile(
"".join(
[
r"\s*((?:INSERT|REPLACE)\b.+\bVALUES?\s*)",
r"(\(\s*(?:%s|%\(.+\)s)\s*(?:,\s*(?:%s|%\(.+\)s)\s*)*\))",
r"(\s*(?:ON DUPLICATE.*)?);?\s*\Z",
]
),
re.IGNORECASE|re.DOTALL,
)
classBaseCursor:
"""A base for Cursor classes. Useful attributes:
description
A tuple of DB API 7-tuples describing the columns in
the last executed query; see PEP-249 for details.
description_flags
Tuple of column flags for last query, one entry per column
in the result set. Values correspond to those in
MySQLdb.constants.FLAG. See MySQL documentation (C API)
for more information. Non-standard extension.
arraysize
default number of rows fetchmany() will fetch
"""
#: Max statement size which :meth:`executemany` generates.
#:
#: Max size of allowed statement is max_allowed_packet - packet_header_size.
#: Default value of max_allowed_packet is 1048576.
max_stmt_length=64*1024
from ._exceptionsimport (
MySQLError,
Warning,
Error,
InterfaceError,
DatabaseError,
DataError,
OperationalError,
IntegrityError,
InternalError,
ProgrammingError,
NotSupportedError,
)
connection=None
def__init__(self, connection):
self.connection=connection
self.description=None
self.description_flags=None
self.rowcount=0
self.arraysize=1
self._executed=None
self.lastrowid=None
self._result=None
self.rownumber=None
self._rows=None
def_discard(self):
self.description=None
self.description_flags=None
# Django uses some member after __exit__.
# So we keep rowcount and lastrowid here. They are cleared in Cursor._query().
# self.rowcount = 0
# self.lastrowid = None
self._rows=None
self.rownumber=None
ifself._result:
self._result.discard()
self._result=None
con=self.connection
ifconisNone:
return
whilecon.next_result() ==0: # -1 means no more data.
con.discard_result()
defclose(self):
"""Close the cursor. No further queries will be possible."""
try:
ifself.connectionisNone:
return
self._discard()
finally:
self.connection=None
self._result=None
def__enter__(self):
returnself
def__exit__(self, *exc_info):
delexc_info
self.close()
def_check_executed(self):
ifnotself._executed:
raiseProgrammingError("execute() first")
defnextset(self):
"""Advance to the next result set.
Returns None if there are no more result sets.
"""
ifself._executed:
self.fetchall()
db=self._get_db()
nr=db.next_result()
ifnr==-1:
returnNone
self._do_get_result(db)
self._post_get_result()
return1
def_do_get_result(self, db):
self._result=result=self._get_result()
ifresultisNone:
self.description=self.description_flags=None
else:
self.description=result.describe()
self.description_flags=result.field_flags()
self.rowcount=db.affected_rows()
self.rownumber=0
self.lastrowid=db.insert_id()
def_post_get_result(self):
pass
defsetinputsizes(self, *args):
"""Does nothing, required by DB API."""
defsetoutputsizes(self, *args):
"""Does nothing, required by DB API."""
def_get_db(self):
con=self.connection
ifconisNone:
raiseProgrammingError("cursor closed")
returncon
defexecute(self, query, args=None):
"""Execute a query.
query -- string, query to execute on server
args -- optional sequence or mapping, parameters to use with query.
Note: If args is a sequence, then %s must be used as the
parameter placeholder in the query. If a mapping is used,
%(key)s must be used as the placeholder.
Returns integer represents rows affected, if any
"""
self._discard()
mogrified_query=self._mogrify(query, args)
assertisinstance(mogrified_query, (bytes, bytearray))
res=self._query(mogrified_query)
returnres
def_mogrify(self, query, args=None):
"""Return query after binding args."""
db=self._get_db()
ifisinstance(query, str):
query=query.encode(db.encoding)
ifargsisnotNone:
ifisinstance(args, dict):
nargs= {}
forkey, iteminargs.items():
ifisinstance(key, str):
key=key.encode(db.encoding)
nargs[key] =db.literal(item)
args=nargs
else:
args=tuple(map(db.literal, args))
try:
query=query%args
exceptTypeErrorasm:
raiseProgrammingError(str(m))
returnquery
defmogrify(self, query, args=None):
"""Return query after binding args.
query -- string, query to mogrify
args -- optional sequence or mapping, parameters to use with query.
Note: If args is a sequence, then %s must be used as the
parameter placeholder in the query. If a mapping is used,
%(key)s must be used as the placeholder.
Returns string representing query that would be executed by the server
"""
returnself._mogrify(query, args).decode(self._get_db().encoding)
defexecutemany(self, query, args):
# type: (str, list) -> int
"""Execute a multi-row query.
:param query: query to execute on server
:param args: Sequence of sequences or mappings. It is used as parameter.
:return: Number of rows affected, if any.
This method improves performance on multiple-row INSERT and
REPLACE. Otherwise it is equivalent to looping over args with
execute().
"""
ifnotargs:
return
m=RE_INSERT_VALUES.match(query)
ifm:
q_prefix=m.group(1) % ()
q_values=m.group(2).rstrip()
q_postfix=m.group(3) or""
assertq_values[0] =="("andq_values[-1] ==")"
returnself._do_execute_many(
q_prefix,
q_values,
q_postfix,
args,
self.max_stmt_length,
self._get_db().encoding,
)
self.rowcount=sum(self.execute(query, arg) forarginargs)
returnself.rowcount
def_do_execute_many(
self, prefix, values, postfix, args, max_stmt_length, encoding
):
ifisinstance(prefix, str):
prefix=prefix.encode(encoding)
ifisinstance(values, str):
values=values.encode(encoding)
ifisinstance(postfix, str):
postfix=postfix.encode(encoding)
sql=bytearray(prefix)
args=iter(args)
v=self._mogrify(values, next(args))
sql+=v
rows=0
forarginargs:
v=self._mogrify(values, arg)
iflen(sql) +len(v) +len(postfix) +1>max_stmt_length:
rows+=self.execute(sql+postfix)
sql=bytearray(prefix)
else:
sql+=b","
sql+=v
rows+=self.execute(sql+postfix)
self.rowcount=rows
returnrows
defcallproc(self, procname, args=()):
"""Execute stored procedure procname with args
procname -- string, name of procedure to execute on server
args -- Sequence of parameters to use with procedure
Returns the original args.
Compatibility warning: PEP-249 specifies that any modified
parameters must be returned. This is currently impossible
as they are only available by storing them in a server
variable and then retrieved by a query. Since stored
procedures return zero or more result sets, there is no
reliable way to get at OUT or INOUT parameters via callproc.
The server variables are named @_procname_n, where procname
is the parameter above and n is the position of the parameter
(from zero). Once all result sets generated by the procedure
have been fetched, you can issue a SELECT @_procname_0, ...
query using .execute() to get any OUT or INOUT values.
Compatibility warning: The act of calling a stored procedure
itself creates an empty result set. This appears after any
result sets generated by the procedure. This is non-standard
behavior with respect to the DB-API. Be sure to use nextset()
to advance through all result sets; otherwise you may get
disconnected.
"""
db=self._get_db()
ifisinstance(procname, str):
procname=procname.encode(db.encoding)
ifargs:
fmt=b"@_"+procname+b"_%d=%s"
q=b"SET %s"%b",".join(
fmt% (index, db.literal(arg)) forindex, arginenumerate(args)
)
self._query(q)
self.nextset()
q=b"CALL %s(%s)"% (
procname,
b",".join([b"@_%s_%d"% (procname, i) foriinrange(len(args))]),
)
self._query(q)
returnargs
def_query(self, q):
db=self._get_db()
self._result=None
self.rowcount=None
self.lastrowid=None
db.query(q)
self._do_get_result(db)
self._post_get_result()
self._executed=q
returnself.rowcount
def_fetch_row(self, size=1):
ifnotself._result:
return ()
returnself._result.fetch_row(size, self._fetch_type)
def__iter__(self):
returniter(self.fetchone, None)
Warning=Warning
Error=Error
InterfaceError=InterfaceError
DatabaseError=DatabaseError
DataError=DataError
OperationalError=OperationalError
IntegrityError=IntegrityError
InternalError=InternalError
ProgrammingError=ProgrammingError
NotSupportedError=NotSupportedError
classCursorStoreResultMixIn:
"""This is a MixIn class which causes the entire result set to be
stored on the client side, i.e. it uses mysql_store_result(). If the
result set can be very large, consider adding a LIMIT clause to your
query, or using CursorUseResultMixIn instead."""
def_get_result(self):
returnself._get_db().store_result()
def_post_get_result(self):
self._rows=self._fetch_row(0)
self._result=None
deffetchone(self):
"""Fetches a single row from the cursor. None indicates that
no more rows are available."""
self._check_executed()
ifself.rownumber>=len(self._rows):
returnNone
result=self._rows[self.rownumber]
self.rownumber=self.rownumber+1
returnresult
deffetchmany(self, size=None):
"""Fetch up to size rows from the cursor. Result set may be smaller
than size. If size is not defined, cursor.arraysize is used."""
self._check_executed()
end=self.rownumber+ (sizeorself.arraysize)
result=self._rows[self.rownumber : end]
self.rownumber=min(end, len(self._rows))
returnresult
deffetchall(self):
"""Fetches all available rows from the cursor."""
self._check_executed()
ifself.rownumber:
result=self._rows[self.rownumber :]
else:
result=self._rows
self.rownumber=len(self._rows)
returnresult
defscroll(self, value, mode="relative"):
"""Scroll the cursor in the result set to a new position according
to mode.
If mode is 'relative' (default), value is taken as offset to
the current position in the result set, if set to 'absolute',
value states an absolute target position."""
self._check_executed()
ifmode=="relative":
r=self.rownumber+value
elifmode=="absolute":
r=value
else:
raiseProgrammingError("unknown scroll mode %s"%repr(mode))
ifr<0orr>=len(self._rows):
raiseIndexError("out of range")
self.rownumber=r
def__iter__(self):
self._check_executed()
result=self.rownumberandself._rows[self.rownumber :] orself._rows
returniter(result)
classCursorUseResultMixIn:
"""This is a MixIn class which causes the result set to be stored
in the server and sent row-by-row to client side, i.e. it uses
mysql_use_result(). You MUST retrieve the entire result set and
close() the cursor before additional queries can be performed on
the connection."""
def_get_result(self):
returnself._get_db().use_result()
deffetchone(self):
"""Fetches a single row from the cursor."""
self._check_executed()
r=self._fetch_row(1)
ifnotr:
returnNone
self.rownumber=self.rownumber+1
returnr[0]
deffetchmany(self, size=None):
"""Fetch up to size rows from the cursor. Result set may be smaller
than size. If size is not defined, cursor.arraysize is used."""
self._check_executed()
r=self._fetch_row(sizeorself.arraysize)
self.rownumber=self.rownumber+len(r)
returnr
deffetchall(self):
"""Fetches all available rows from the cursor."""
self._check_executed()
r=self._fetch_row(0)
self.rownumber=self.rownumber+len(r)
returnr
def__iter__(self):
returnself
defnext(self):
row=self.fetchone()
ifrowisNone:
raiseStopIteration
returnrow
__next__=next
classCursorTupleRowsMixIn:
"""This is a MixIn class that causes all rows to be returned as tuples,
which is the standard form required by DB API."""
_fetch_type=0
classCursorDictRowsMixIn:
"""This is a MixIn class that causes all rows to be returned as
dictionaries. This is a non-standard feature."""
_fetch_type=1
classCursor(CursorStoreResultMixIn, CursorTupleRowsMixIn, BaseCursor):
"""This is the standard Cursor class that returns rows as tuples
and stores the result set in the client."""
classDictCursor(CursorStoreResultMixIn, CursorDictRowsMixIn, BaseCursor):
"""This is a Cursor class that returns rows as dictionaries and
stores the result set in the client."""
classSSCursor(CursorUseResultMixIn, CursorTupleRowsMixIn, BaseCursor):
"""This is a Cursor class that returns rows as tuples and stores
the result set in the server."""
classSSDictCursor(CursorUseResultMixIn, CursorDictRowsMixIn, BaseCursor):
"""This is a Cursor class that returns rows as dictionaries and
stores the result set in the server."""