cursors.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. import re
  2. import warnings
  3. from . import err
  4. #: Regular expression for :meth:`Cursor.executemany`.
  5. #: executemany only supports simple bulk insert.
  6. #: You can use it to load large dataset.
  7. RE_INSERT_VALUES = re.compile(
  8. r"\s*((?:INSERT|REPLACE)\b.+\bVALUES?\s*)"
  9. + r"(\(\s*(?:%s|%\(.+\)s)\s*(?:,\s*(?:%s|%\(.+\)s)\s*)*\))"
  10. + r"(\s*(?:ON DUPLICATE.*)?);?\s*\Z",
  11. re.IGNORECASE | re.DOTALL,
  12. )
  13. class Cursor:
  14. """
  15. This is the object used to interact with the database.
  16. Do not create an instance of a Cursor yourself. Call
  17. connections.Connection.cursor().
  18. See `Cursor <https://www.python.org/dev/peps/pep-0249/#cursor-objects>`_ in
  19. the specification.
  20. """
  21. #: Max statement size which :meth:`executemany` generates.
  22. #:
  23. #: Max size of allowed statement is max_allowed_packet - packet_header_size.
  24. #: Default value of max_allowed_packet is 1048576.
  25. max_stmt_length = 1024000
  26. def __init__(self, connection):
  27. self.connection = connection
  28. self.warning_count = 0
  29. self.description = None
  30. self.rownumber = 0
  31. self.rowcount = -1
  32. self.arraysize = 1
  33. self._executed = None
  34. self._result = None
  35. self._rows = None
  36. def close(self):
  37. """
  38. Closing a cursor just exhausts all remaining data.
  39. """
  40. conn = self.connection
  41. if conn is None:
  42. return
  43. try:
  44. while self.nextset():
  45. pass
  46. finally:
  47. self.connection = None
  48. def __enter__(self):
  49. return self
  50. def __exit__(self, *exc_info):
  51. del exc_info
  52. self.close()
  53. def _get_db(self):
  54. if not self.connection:
  55. raise err.ProgrammingError("Cursor closed")
  56. return self.connection
  57. def _check_executed(self):
  58. if not self._executed:
  59. raise err.ProgrammingError("execute() first")
  60. def _conv_row(self, row):
  61. return row
  62. def setinputsizes(self, *args):
  63. """Does nothing, required by DB API."""
  64. def setoutputsizes(self, *args):
  65. """Does nothing, required by DB API."""
  66. def _nextset(self, unbuffered=False):
  67. """Get the next query set."""
  68. conn = self._get_db()
  69. current_result = self._result
  70. if current_result is None or current_result is not conn._result:
  71. return None
  72. if not current_result.has_next:
  73. return None
  74. self._result = None
  75. self._clear_result()
  76. conn.next_result(unbuffered=unbuffered)
  77. self._do_get_result()
  78. return True
  79. def nextset(self):
  80. return self._nextset(False)
  81. def _escape_args(self, args, conn):
  82. if isinstance(args, (tuple, list)):
  83. return tuple(conn.literal(arg) for arg in args)
  84. elif isinstance(args, dict):
  85. return {key: conn.literal(val) for (key, val) in args.items()}
  86. else:
  87. # If it's not a dictionary let's try escaping it anyways.
  88. # Worst case it will throw a Value error
  89. return conn.escape(args)
  90. def mogrify(self, query, args=None):
  91. """
  92. Returns the exact string that would be sent to the database by calling the
  93. execute() method.
  94. :param query: Query to mogrify.
  95. :type query: str
  96. :param args: Parameters used with query. (optional)
  97. :type args: tuple, list or dict
  98. :return: The query with argument binding applied.
  99. :rtype: str
  100. This method follows the extension to the DB API 2.0 followed by Psycopg.
  101. """
  102. conn = self._get_db()
  103. if args is not None:
  104. query = query % self._escape_args(args, conn)
  105. return query
  106. def execute(self, query, args=None):
  107. """Execute a query.
  108. :param query: Query to execute.
  109. :type query: str
  110. :param args: Parameters used with query. (optional)
  111. :type args: tuple, list or dict
  112. :return: Number of affected rows.
  113. :rtype: int
  114. If args is a list or tuple, %s can be used as a placeholder in the query.
  115. If args is a dict, %(name)s can be used as a placeholder in the query.
  116. """
  117. while self.nextset():
  118. pass
  119. query = self.mogrify(query, args)
  120. result = self._query(query)
  121. self._executed = query
  122. return result
  123. def executemany(self, query, args):
  124. """Run several data against one query.
  125. :param query: Query to execute.
  126. :type query: str
  127. :param args: Sequence of sequences or mappings. It is used as parameter.
  128. :type args: tuple or list
  129. :return: Number of rows affected, if any.
  130. :rtype: int or None
  131. This method improves performance on multiple-row INSERT and
  132. REPLACE. Otherwise it is equivalent to looping over args with
  133. execute().
  134. """
  135. if not args:
  136. return
  137. m = RE_INSERT_VALUES.match(query)
  138. if m:
  139. q_prefix = m.group(1) % ()
  140. q_values = m.group(2).rstrip()
  141. q_postfix = m.group(3) or ""
  142. assert q_values[0] == "(" and q_values[-1] == ")"
  143. return self._do_execute_many(
  144. q_prefix,
  145. q_values,
  146. q_postfix,
  147. args,
  148. self.max_stmt_length,
  149. self._get_db().encoding,
  150. )
  151. self.rowcount = sum(self.execute(query, arg) for arg in args)
  152. return self.rowcount
  153. def _do_execute_many(
  154. self, prefix, values, postfix, args, max_stmt_length, encoding
  155. ):
  156. conn = self._get_db()
  157. escape = self._escape_args
  158. if isinstance(prefix, str):
  159. prefix = prefix.encode(encoding)
  160. if isinstance(postfix, str):
  161. postfix = postfix.encode(encoding)
  162. sql = bytearray(prefix)
  163. args = iter(args)
  164. v = values % escape(next(args), conn)
  165. if isinstance(v, str):
  166. v = v.encode(encoding, "surrogateescape")
  167. sql += v
  168. rows = 0
  169. for arg in args:
  170. v = values % escape(arg, conn)
  171. if isinstance(v, str):
  172. v = v.encode(encoding, "surrogateescape")
  173. if len(sql) + len(v) + len(postfix) + 1 > max_stmt_length:
  174. rows += self.execute(sql + postfix)
  175. sql = bytearray(prefix)
  176. else:
  177. sql += b","
  178. sql += v
  179. rows += self.execute(sql + postfix)
  180. self.rowcount = rows
  181. return rows
  182. def callproc(self, procname, args=()):
  183. """Execute stored procedure procname with args.
  184. :param procname: Name of procedure to execute on server.
  185. :type procname: str
  186. :param args: Sequence of parameters to use with procedure.
  187. :type args: tuple or list
  188. Returns the original args.
  189. Compatibility warning: PEP-249 specifies that any modified
  190. parameters must be returned. This is currently impossible
  191. as they are only available by storing them in a server
  192. variable and then retrieved by a query. Since stored
  193. procedures return zero or more result sets, there is no
  194. reliable way to get at OUT or INOUT parameters via callproc.
  195. The server variables are named @_procname_n, where procname
  196. is the parameter above and n is the position of the parameter
  197. (from zero). Once all result sets generated by the procedure
  198. have been fetched, you can issue a SELECT @_procname_0, ...
  199. query using .execute() to get any OUT or INOUT values.
  200. Compatibility warning: The act of calling a stored procedure
  201. itself creates an empty result set. This appears after any
  202. result sets generated by the procedure. This is non-standard
  203. behavior with respect to the DB-API. Be sure to use nextset()
  204. to advance through all result sets; otherwise you may get
  205. disconnected.
  206. """
  207. conn = self._get_db()
  208. if args:
  209. fmt = f"@_{procname}_%d=%s"
  210. self._query(
  211. "SET %s"
  212. % ",".join(
  213. fmt % (index, conn.escape(arg)) for index, arg in enumerate(args)
  214. )
  215. )
  216. self.nextset()
  217. q = "CALL {}({})".format(
  218. procname,
  219. ",".join(["@_%s_%d" % (procname, i) for i in range(len(args))]),
  220. )
  221. self._query(q)
  222. self._executed = q
  223. return args
  224. def fetchone(self):
  225. """Fetch the next row."""
  226. self._check_executed()
  227. if self._rows is None or self.rownumber >= len(self._rows):
  228. return None
  229. result = self._rows[self.rownumber]
  230. self.rownumber += 1
  231. return result
  232. def fetchmany(self, size=None):
  233. """Fetch several rows."""
  234. self._check_executed()
  235. if self._rows is None:
  236. # Django expects () for EOF.
  237. # https://github.com/django/django/blob/0c1518ee429b01c145cf5b34eab01b0b92f8c246/django/db/backends/mysql/features.py#L8
  238. return ()
  239. end = self.rownumber + (size or self.arraysize)
  240. result = self._rows[self.rownumber : end]
  241. self.rownumber = min(end, len(self._rows))
  242. return result
  243. def fetchall(self):
  244. """Fetch all the rows."""
  245. self._check_executed()
  246. if self._rows is None:
  247. return []
  248. if self.rownumber:
  249. result = self._rows[self.rownumber :]
  250. else:
  251. result = self._rows
  252. self.rownumber = len(self._rows)
  253. return result
  254. def scroll(self, value, mode="relative"):
  255. self._check_executed()
  256. if mode == "relative":
  257. r = self.rownumber + value
  258. elif mode == "absolute":
  259. r = value
  260. else:
  261. raise err.ProgrammingError("unknown scroll mode %s" % mode)
  262. if not (0 <= r < len(self._rows)):
  263. raise IndexError("out of range")
  264. self.rownumber = r
  265. def _query(self, q):
  266. conn = self._get_db()
  267. self._clear_result()
  268. conn.query(q)
  269. self._do_get_result()
  270. return self.rowcount
  271. def _clear_result(self):
  272. self.rownumber = 0
  273. self._result = None
  274. self.rowcount = 0
  275. self.warning_count = 0
  276. self.description = None
  277. self.lastrowid = None
  278. self._rows = None
  279. def _do_get_result(self):
  280. conn = self._get_db()
  281. self._result = result = conn._result
  282. self.rowcount = result.affected_rows
  283. self.warning_count = result.warning_count
  284. self.description = result.description
  285. self.lastrowid = result.insert_id
  286. self._rows = result.rows
  287. def __iter__(self):
  288. return self
  289. def __next__(self):
  290. row = self.fetchone()
  291. if row is None:
  292. raise StopIteration
  293. return row
  294. def __getattr__(self, name):
  295. # DB-API 2.0 optional extension says these errors can be accessed
  296. # via Connection object. But MySQLdb had defined them on Cursor object.
  297. if name in (
  298. "Warning",
  299. "Error",
  300. "InterfaceError",
  301. "DatabaseError",
  302. "DataError",
  303. "OperationalError",
  304. "IntegrityError",
  305. "InternalError",
  306. "ProgrammingError",
  307. "NotSupportedError",
  308. ):
  309. # Deprecated since v1.1
  310. warnings.warn(
  311. "PyMySQL errors hould be accessed from `pymysql` package",
  312. DeprecationWarning,
  313. stacklevel=2,
  314. )
  315. return getattr(err, name)
  316. raise AttributeError(name)
  317. class DictCursorMixin:
  318. # You can override this to use OrderedDict or other dict-like types.
  319. dict_type = dict
  320. def _do_get_result(self):
  321. super()._do_get_result()
  322. fields = []
  323. if self.description:
  324. for f in self._result.fields:
  325. name = f.name
  326. if name in fields:
  327. name = f.table_name + "." + name
  328. fields.append(name)
  329. self._fields = fields
  330. if fields and self._rows:
  331. self._rows = [self._conv_row(r) for r in self._rows]
  332. def _conv_row(self, row):
  333. if row is None:
  334. return None
  335. return self.dict_type(zip(self._fields, row))
  336. class DictCursor(DictCursorMixin, Cursor):
  337. """A cursor which returns results as a dictionary"""
  338. class SSCursor(Cursor):
  339. """
  340. Unbuffered Cursor, mainly useful for queries that return a lot of data,
  341. or for connections to remote servers over a slow network.
  342. Instead of copying every row of data into a buffer, this will fetch
  343. rows as needed. The upside of this is the client uses much less memory,
  344. and rows are returned much faster when traveling over a slow network
  345. or if the result set is very big.
  346. There are limitations, though. The MySQL protocol doesn't support
  347. returning the total number of rows, so the only way to tell how many rows
  348. there are is to iterate over every row returned. Also, it currently isn't
  349. possible to scroll backwards, as only the current row is held in memory.
  350. """
  351. def _conv_row(self, row):
  352. return row
  353. def close(self):
  354. conn = self.connection
  355. if conn is None:
  356. return
  357. if self._result is not None and self._result is conn._result:
  358. self._result._finish_unbuffered_query()
  359. try:
  360. while self.nextset():
  361. pass
  362. finally:
  363. self.connection = None
  364. __del__ = close
  365. def _query(self, q):
  366. conn = self._get_db()
  367. self._clear_result()
  368. conn.query(q, unbuffered=True)
  369. self._do_get_result()
  370. return self.rowcount
  371. def nextset(self):
  372. return self._nextset(unbuffered=True)
  373. def read_next(self):
  374. """Read next row."""
  375. return self._conv_row(self._result._read_rowdata_packet_unbuffered())
  376. def fetchone(self):
  377. """Fetch next row."""
  378. self._check_executed()
  379. row = self.read_next()
  380. if row is None:
  381. self.warning_count = self._result.warning_count
  382. return None
  383. self.rownumber += 1
  384. return row
  385. def fetchall(self):
  386. """
  387. Fetch all, as per MySQLdb. Pretty useless for large queries, as
  388. it is buffered. See fetchall_unbuffered(), if you want an unbuffered
  389. generator version of this method.
  390. """
  391. return list(self.fetchall_unbuffered())
  392. def fetchall_unbuffered(self):
  393. """
  394. Fetch all, implemented as a generator, which isn't to standard,
  395. however, it doesn't make sense to return everything in a list, as that
  396. would use ridiculous memory for large result sets.
  397. """
  398. return iter(self.fetchone, None)
  399. def fetchmany(self, size=None):
  400. """Fetch many."""
  401. self._check_executed()
  402. if size is None:
  403. size = self.arraysize
  404. rows = []
  405. for i in range(size):
  406. row = self.read_next()
  407. if row is None:
  408. self.warning_count = self._result.warning_count
  409. break
  410. rows.append(row)
  411. self.rownumber += 1
  412. if not rows:
  413. # Django expects () for EOF.
  414. # https://github.com/django/django/blob/0c1518ee429b01c145cf5b34eab01b0b92f8c246/django/db/backends/mysql/features.py#L8
  415. return ()
  416. return rows
  417. def scroll(self, value, mode="relative"):
  418. self._check_executed()
  419. if mode == "relative":
  420. if value < 0:
  421. raise err.NotSupportedError(
  422. "Backwards scrolling not supported by this cursor"
  423. )
  424. for _ in range(value):
  425. self.read_next()
  426. self.rownumber += value
  427. elif mode == "absolute":
  428. if value < self.rownumber:
  429. raise err.NotSupportedError(
  430. "Backwards scrolling not supported by this cursor"
  431. )
  432. end = value - self.rownumber
  433. for _ in range(end):
  434. self.read_next()
  435. self.rownumber = value
  436. else:
  437. raise err.ProgrammingError("unknown scroll mode %s" % mode)
  438. class SSDictCursor(DictCursorMixin, SSCursor):
  439. """An unbuffered cursor, which returns results as a dictionary"""