cursors.py 15 KB

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