cursors.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. """MySQLdb Cursors
  2. This module implements Cursors of various types for MySQLdb. By
  3. default, MySQLdb uses the Cursor class.
  4. """
  5. import re
  6. from ._exceptions import ProgrammingError
  7. #: Regular expression for ``Cursor.executemany```.
  8. #: executemany only supports simple bulk insert.
  9. #: You can use it to load large dataset.
  10. RE_INSERT_VALUES = re.compile(
  11. "".join(
  12. [
  13. r"\s*((?:INSERT|REPLACE)\b.+\bVALUES?\s*)",
  14. r"(\(\s*(?:%s|%\(.+\)s)\s*(?:,\s*(?:%s|%\(.+\)s)\s*)*\))",
  15. r"(\s*(?:ON DUPLICATE.*)?);?\s*\Z",
  16. ]
  17. ),
  18. re.IGNORECASE | re.DOTALL,
  19. )
  20. class BaseCursor:
  21. """A base for Cursor classes. Useful attributes:
  22. description
  23. A tuple of DB API 7-tuples describing the columns in
  24. the last executed query; see PEP-249 for details.
  25. description_flags
  26. Tuple of column flags for last query, one entry per column
  27. in the result set. Values correspond to those in
  28. MySQLdb.constants.FLAG. See MySQL documentation (C API)
  29. for more information. Non-standard extension.
  30. arraysize
  31. default number of rows fetchmany() will fetch
  32. """
  33. #: Max statement size which :meth:`executemany` generates.
  34. #:
  35. #: Max size of allowed statement is max_allowed_packet - packet_header_size.
  36. #: Default value of max_allowed_packet is 1048576.
  37. max_stmt_length = 64 * 1024
  38. from ._exceptions import (
  39. MySQLError,
  40. Warning,
  41. Error,
  42. InterfaceError,
  43. DatabaseError,
  44. DataError,
  45. OperationalError,
  46. IntegrityError,
  47. InternalError,
  48. ProgrammingError,
  49. NotSupportedError,
  50. )
  51. connection = None
  52. def __init__(self, connection):
  53. self.connection = connection
  54. self.description = None
  55. self.description_flags = None
  56. self.rowcount = 0
  57. self.arraysize = 1
  58. self._executed = None
  59. self.lastrowid = None
  60. self._result = None
  61. self.rownumber = None
  62. self._rows = None
  63. def _discard(self):
  64. self.description = None
  65. self.description_flags = None
  66. # Django uses some member after __exit__.
  67. # So we keep rowcount and lastrowid here. They are cleared in Cursor._query().
  68. # self.rowcount = 0
  69. # self.lastrowid = None
  70. self._rows = None
  71. self.rownumber = None
  72. if self._result:
  73. self._result.discard()
  74. self._result = None
  75. con = self.connection
  76. if con is None:
  77. return
  78. while con.next_result() == 0: # -1 means no more data.
  79. con.discard_result()
  80. def close(self):
  81. """Close the cursor. No further queries will be possible."""
  82. try:
  83. if self.connection is None:
  84. return
  85. self._discard()
  86. finally:
  87. self.connection = None
  88. self._result = None
  89. def __enter__(self):
  90. return self
  91. def __exit__(self, *exc_info):
  92. del exc_info
  93. self.close()
  94. def _check_executed(self):
  95. if not self._executed:
  96. raise ProgrammingError("execute() first")
  97. def nextset(self):
  98. """Advance to the next result set.
  99. Returns None if there are no more result sets.
  100. """
  101. if self._executed:
  102. self.fetchall()
  103. db = self._get_db()
  104. nr = db.next_result()
  105. if nr == -1:
  106. return None
  107. self._do_get_result(db)
  108. self._post_get_result()
  109. return 1
  110. def _do_get_result(self, db):
  111. self._result = result = self._get_result()
  112. if result is None:
  113. self.description = self.description_flags = None
  114. else:
  115. self.description = result.describe()
  116. self.description_flags = result.field_flags()
  117. self.rowcount = db.affected_rows()
  118. self.rownumber = 0
  119. self.lastrowid = db.insert_id()
  120. def _post_get_result(self):
  121. pass
  122. def setinputsizes(self, *args):
  123. """Does nothing, required by DB API."""
  124. def setoutputsizes(self, *args):
  125. """Does nothing, required by DB API."""
  126. def _get_db(self):
  127. con = self.connection
  128. if con is None:
  129. raise ProgrammingError("cursor closed")
  130. return con
  131. def execute(self, query, args=None):
  132. """Execute a query.
  133. query -- string, query to execute on server
  134. args -- optional sequence or mapping, parameters to use with query.
  135. Note: If args is a sequence, then %s must be used as the
  136. parameter placeholder in the query. If a mapping is used,
  137. %(key)s must be used as the placeholder.
  138. Returns integer represents rows affected, if any
  139. """
  140. self._discard()
  141. mogrified_query = self._mogrify(query, args)
  142. assert isinstance(mogrified_query, (bytes, bytearray))
  143. res = self._query(mogrified_query)
  144. return res
  145. def _mogrify(self, query, args=None):
  146. """Return query after binding args."""
  147. db = self._get_db()
  148. if isinstance(query, str):
  149. query = query.encode(db.encoding)
  150. if args is not None:
  151. if isinstance(args, dict):
  152. nargs = {}
  153. for key, item in args.items():
  154. if isinstance(key, str):
  155. key = key.encode(db.encoding)
  156. nargs[key] = db.literal(item)
  157. args = nargs
  158. else:
  159. args = tuple(map(db.literal, args))
  160. try:
  161. query = query % args
  162. except TypeError as m:
  163. raise ProgrammingError(str(m))
  164. return query
  165. def mogrify(self, query, args=None):
  166. """Return query after binding args.
  167. query -- string, query to mogrify
  168. args -- optional sequence or mapping, parameters to use with query.
  169. Note: If args is a sequence, then %s must be used as the
  170. parameter placeholder in the query. If a mapping is used,
  171. %(key)s must be used as the placeholder.
  172. Returns string representing query that would be executed by the server
  173. """
  174. return self._mogrify(query, args).decode(self._get_db().encoding)
  175. def executemany(self, query, args):
  176. # type: (str, list) -> int
  177. """Execute a multi-row query.
  178. :param query: query to execute on server
  179. :param args: Sequence of sequences or mappings. It is used as parameter.
  180. :return: Number of rows affected, if any.
  181. This method improves performance on multiple-row INSERT and
  182. REPLACE. Otherwise it is equivalent to looping over args with
  183. execute().
  184. """
  185. if not args:
  186. return
  187. m = RE_INSERT_VALUES.match(query)
  188. if m:
  189. q_prefix = m.group(1) % ()
  190. q_values = m.group(2).rstrip()
  191. q_postfix = m.group(3) or ""
  192. assert q_values[0] == "(" and q_values[-1] == ")"
  193. return self._do_execute_many(
  194. q_prefix,
  195. q_values,
  196. q_postfix,
  197. args,
  198. self.max_stmt_length,
  199. self._get_db().encoding,
  200. )
  201. self.rowcount = sum(self.execute(query, arg) for arg in args)
  202. return self.rowcount
  203. def _do_execute_many(
  204. self, prefix, values, postfix, args, max_stmt_length, encoding
  205. ):
  206. if isinstance(prefix, str):
  207. prefix = prefix.encode(encoding)
  208. if isinstance(values, str):
  209. values = values.encode(encoding)
  210. if isinstance(postfix, str):
  211. postfix = postfix.encode(encoding)
  212. sql = bytearray(prefix)
  213. args = iter(args)
  214. v = self._mogrify(values, next(args))
  215. sql += v
  216. rows = 0
  217. for arg in args:
  218. v = self._mogrify(values, arg)
  219. if len(sql) + len(v) + len(postfix) + 1 > max_stmt_length:
  220. rows += self.execute(sql + postfix)
  221. sql = bytearray(prefix)
  222. else:
  223. sql += b","
  224. sql += v
  225. rows += self.execute(sql + postfix)
  226. self.rowcount = rows
  227. return rows
  228. def callproc(self, procname, args=()):
  229. """Execute stored procedure procname with args
  230. procname -- string, name of procedure to execute on server
  231. args -- Sequence of parameters to use with procedure
  232. Returns the original args.
  233. Compatibility warning: PEP-249 specifies that any modified
  234. parameters must be returned. This is currently impossible
  235. as they are only available by storing them in a server
  236. variable and then retrieved by a query. Since stored
  237. procedures return zero or more result sets, there is no
  238. reliable way to get at OUT or INOUT parameters via callproc.
  239. The server variables are named @_procname_n, where procname
  240. is the parameter above and n is the position of the parameter
  241. (from zero). Once all result sets generated by the procedure
  242. have been fetched, you can issue a SELECT @_procname_0, ...
  243. query using .execute() to get any OUT or INOUT values.
  244. Compatibility warning: The act of calling a stored procedure
  245. itself creates an empty result set. This appears after any
  246. result sets generated by the procedure. This is non-standard
  247. behavior with respect to the DB-API. Be sure to use nextset()
  248. to advance through all result sets; otherwise you may get
  249. disconnected.
  250. """
  251. db = self._get_db()
  252. if isinstance(procname, str):
  253. procname = procname.encode(db.encoding)
  254. if args:
  255. fmt = b"@_" + procname + b"_%d=%s"
  256. q = b"SET %s" % b",".join(
  257. fmt % (index, db.literal(arg)) for index, arg in enumerate(args)
  258. )
  259. self._query(q)
  260. self.nextset()
  261. q = b"CALL %s(%s)" % (
  262. procname,
  263. b",".join([b"@_%s_%d" % (procname, i) for i in range(len(args))]),
  264. )
  265. self._query(q)
  266. return args
  267. def _query(self, q):
  268. db = self._get_db()
  269. self._result = None
  270. self.rowcount = None
  271. self.lastrowid = None
  272. db.query(q)
  273. self._do_get_result(db)
  274. self._post_get_result()
  275. self._executed = q
  276. return self.rowcount
  277. def _fetch_row(self, size=1):
  278. if not self._result:
  279. return ()
  280. return self._result.fetch_row(size, self._fetch_type)
  281. def __iter__(self):
  282. return iter(self.fetchone, None)
  283. Warning = Warning
  284. Error = Error
  285. InterfaceError = InterfaceError
  286. DatabaseError = DatabaseError
  287. DataError = DataError
  288. OperationalError = OperationalError
  289. IntegrityError = IntegrityError
  290. InternalError = InternalError
  291. ProgrammingError = ProgrammingError
  292. NotSupportedError = NotSupportedError
  293. class CursorStoreResultMixIn:
  294. """This is a MixIn class which causes the entire result set to be
  295. stored on the client side, i.e. it uses mysql_store_result(). If the
  296. result set can be very large, consider adding a LIMIT clause to your
  297. query, or using CursorUseResultMixIn instead."""
  298. def _get_result(self):
  299. return self._get_db().store_result()
  300. def _post_get_result(self):
  301. self._rows = self._fetch_row(0)
  302. self._result = None
  303. def fetchone(self):
  304. """Fetches a single row from the cursor. None indicates that
  305. no more rows are available."""
  306. self._check_executed()
  307. if self.rownumber >= len(self._rows):
  308. return None
  309. result = self._rows[self.rownumber]
  310. self.rownumber = self.rownumber + 1
  311. return result
  312. def fetchmany(self, size=None):
  313. """Fetch up to size rows from the cursor. Result set may be smaller
  314. than size. If size is not defined, cursor.arraysize is used."""
  315. self._check_executed()
  316. end = self.rownumber + (size or self.arraysize)
  317. result = self._rows[self.rownumber : end]
  318. self.rownumber = min(end, len(self._rows))
  319. return result
  320. def fetchall(self):
  321. """Fetches all available rows from the cursor."""
  322. self._check_executed()
  323. if self.rownumber:
  324. result = self._rows[self.rownumber :]
  325. else:
  326. result = self._rows
  327. self.rownumber = len(self._rows)
  328. return result
  329. def scroll(self, value, mode="relative"):
  330. """Scroll the cursor in the result set to a new position according
  331. to mode.
  332. If mode is 'relative' (default), value is taken as offset to
  333. the current position in the result set, if set to 'absolute',
  334. value states an absolute target position."""
  335. self._check_executed()
  336. if mode == "relative":
  337. r = self.rownumber + value
  338. elif mode == "absolute":
  339. r = value
  340. else:
  341. raise ProgrammingError("unknown scroll mode %s" % repr(mode))
  342. if r < 0 or r >= len(self._rows):
  343. raise IndexError("out of range")
  344. self.rownumber = r
  345. def __iter__(self):
  346. self._check_executed()
  347. result = self.rownumber and self._rows[self.rownumber :] or self._rows
  348. return iter(result)
  349. class CursorUseResultMixIn:
  350. """This is a MixIn class which causes the result set to be stored
  351. in the server and sent row-by-row to client side, i.e. it uses
  352. mysql_use_result(). You MUST retrieve the entire result set and
  353. close() the cursor before additional queries can be performed on
  354. the connection."""
  355. def _get_result(self):
  356. return self._get_db().use_result()
  357. def fetchone(self):
  358. """Fetches a single row from the cursor."""
  359. self._check_executed()
  360. r = self._fetch_row(1)
  361. if not r:
  362. return None
  363. self.rownumber = self.rownumber + 1
  364. return r[0]
  365. def fetchmany(self, size=None):
  366. """Fetch up to size rows from the cursor. Result set may be smaller
  367. than size. If size is not defined, cursor.arraysize is used."""
  368. self._check_executed()
  369. r = self._fetch_row(size or self.arraysize)
  370. self.rownumber = self.rownumber + len(r)
  371. return r
  372. def fetchall(self):
  373. """Fetches all available rows from the cursor."""
  374. self._check_executed()
  375. r = self._fetch_row(0)
  376. self.rownumber = self.rownumber + len(r)
  377. return r
  378. def __iter__(self):
  379. return self
  380. def next(self):
  381. row = self.fetchone()
  382. if row is None:
  383. raise StopIteration
  384. return row
  385. __next__ = next
  386. class CursorTupleRowsMixIn:
  387. """This is a MixIn class that causes all rows to be returned as tuples,
  388. which is the standard form required by DB API."""
  389. _fetch_type = 0
  390. class CursorDictRowsMixIn:
  391. """This is a MixIn class that causes all rows to be returned as
  392. dictionaries. This is a non-standard feature."""
  393. _fetch_type = 1
  394. class Cursor(CursorStoreResultMixIn, CursorTupleRowsMixIn, BaseCursor):
  395. """This is the standard Cursor class that returns rows as tuples
  396. and stores the result set in the client."""
  397. class DictCursor(CursorStoreResultMixIn, CursorDictRowsMixIn, BaseCursor):
  398. """This is a Cursor class that returns rows as dictionaries and
  399. stores the result set in the client."""
  400. class SSCursor(CursorUseResultMixIn, CursorTupleRowsMixIn, BaseCursor):
  401. """This is a Cursor class that returns rows as tuples and stores
  402. the result set in the server."""
  403. class SSDictCursor(CursorUseResultMixIn, CursorDictRowsMixIn, BaseCursor):
  404. """This is a Cursor class that returns rows as dictionaries and
  405. stores the result set in the server."""