mysqlconnector.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. # mysql/mysqlconnector.py
  2. # Copyright (C) 2005-2022 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. r"""
  8. .. dialect:: mysql+mysqlconnector
  9. :name: MySQL Connector/Python
  10. :dbapi: myconnpy
  11. :connectstring: mysql+mysqlconnector://<user>:<password>@<host>[:<port>]/<dbname>
  12. :url: https://pypi.org/project/mysql-connector-python/
  13. .. note::
  14. The MySQL Connector/Python DBAPI has had many issues since its release,
  15. some of which may remain unresolved, and the mysqlconnector dialect is
  16. **not tested as part of SQLAlchemy's continuous integration**.
  17. The recommended MySQL dialects are mysqlclient and PyMySQL.
  18. """ # noqa
  19. import re
  20. from .base import BIT
  21. from .base import MySQLCompiler
  22. from .base import MySQLDialect
  23. from .base import MySQLIdentifierPreparer
  24. from ... import processors
  25. from ... import util
  26. class MySQLCompiler_mysqlconnector(MySQLCompiler):
  27. def visit_mod_binary(self, binary, operator, **kw):
  28. if self.dialect._mysqlconnector_double_percents:
  29. return (
  30. self.process(binary.left, **kw)
  31. + " %% "
  32. + self.process(binary.right, **kw)
  33. )
  34. else:
  35. return (
  36. self.process(binary.left, **kw)
  37. + " % "
  38. + self.process(binary.right, **kw)
  39. )
  40. def post_process_text(self, text):
  41. if self.dialect._mysqlconnector_double_percents:
  42. return text.replace("%", "%%")
  43. else:
  44. return text
  45. def escape_literal_column(self, text):
  46. if self.dialect._mysqlconnector_double_percents:
  47. return text.replace("%", "%%")
  48. else:
  49. return text
  50. class MySQLIdentifierPreparer_mysqlconnector(MySQLIdentifierPreparer):
  51. @property
  52. def _double_percents(self):
  53. return self.dialect._mysqlconnector_double_percents
  54. @_double_percents.setter
  55. def _double_percents(self, value):
  56. pass
  57. def _escape_identifier(self, value):
  58. value = value.replace(self.escape_quote, self.escape_to_quote)
  59. if self.dialect._mysqlconnector_double_percents:
  60. return value.replace("%", "%%")
  61. else:
  62. return value
  63. class _myconnpyBIT(BIT):
  64. def result_processor(self, dialect, coltype):
  65. """MySQL-connector already converts mysql bits, so."""
  66. return None
  67. class MySQLDialect_mysqlconnector(MySQLDialect):
  68. driver = "mysqlconnector"
  69. supports_statement_cache = True
  70. supports_unicode_binds = True
  71. supports_sane_rowcount = True
  72. supports_sane_multi_rowcount = True
  73. supports_native_decimal = True
  74. default_paramstyle = "format"
  75. statement_compiler = MySQLCompiler_mysqlconnector
  76. preparer = MySQLIdentifierPreparer_mysqlconnector
  77. colspecs = util.update_copy(MySQLDialect.colspecs, {BIT: _myconnpyBIT})
  78. def __init__(self, *arg, **kw):
  79. super(MySQLDialect_mysqlconnector, self).__init__(*arg, **kw)
  80. # hack description encoding since mysqlconnector randomly
  81. # returns bytes or not
  82. self._description_decoder = (
  83. processors.to_conditional_unicode_processor_factory
  84. )(self.description_encoding)
  85. def _check_unicode_description(self, connection):
  86. # hack description encoding since mysqlconnector randomly
  87. # returns bytes or not
  88. return False
  89. @property
  90. def description_encoding(self):
  91. # total guess
  92. return "latin-1"
  93. @util.memoized_property
  94. def supports_unicode_statements(self):
  95. return util.py3k or self._mysqlconnector_version_info > (2, 0)
  96. @classmethod
  97. def dbapi(cls):
  98. from mysql import connector
  99. return connector
  100. def do_ping(self, dbapi_connection):
  101. try:
  102. dbapi_connection.ping(False)
  103. except self.dbapi.Error as err:
  104. if self.is_disconnect(err, dbapi_connection, None):
  105. return False
  106. else:
  107. raise
  108. else:
  109. return True
  110. def create_connect_args(self, url):
  111. opts = url.translate_connect_args(username="user")
  112. opts.update(url.query)
  113. util.coerce_kw_type(opts, "allow_local_infile", bool)
  114. util.coerce_kw_type(opts, "autocommit", bool)
  115. util.coerce_kw_type(opts, "buffered", bool)
  116. util.coerce_kw_type(opts, "compress", bool)
  117. util.coerce_kw_type(opts, "connection_timeout", int)
  118. util.coerce_kw_type(opts, "connect_timeout", int)
  119. util.coerce_kw_type(opts, "consume_results", bool)
  120. util.coerce_kw_type(opts, "force_ipv6", bool)
  121. util.coerce_kw_type(opts, "get_warnings", bool)
  122. util.coerce_kw_type(opts, "pool_reset_session", bool)
  123. util.coerce_kw_type(opts, "pool_size", int)
  124. util.coerce_kw_type(opts, "raise_on_warnings", bool)
  125. util.coerce_kw_type(opts, "raw", bool)
  126. util.coerce_kw_type(opts, "ssl_verify_cert", bool)
  127. util.coerce_kw_type(opts, "use_pure", bool)
  128. util.coerce_kw_type(opts, "use_unicode", bool)
  129. # unfortunately, MySQL/connector python refuses to release a
  130. # cursor without reading fully, so non-buffered isn't an option
  131. opts.setdefault("buffered", True)
  132. # FOUND_ROWS must be set in ClientFlag to enable
  133. # supports_sane_rowcount.
  134. if self.dbapi is not None:
  135. try:
  136. from mysql.connector.constants import ClientFlag
  137. client_flags = opts.get(
  138. "client_flags", ClientFlag.get_default()
  139. )
  140. client_flags |= ClientFlag.FOUND_ROWS
  141. opts["client_flags"] = client_flags
  142. except Exception:
  143. pass
  144. return [[], opts]
  145. @util.memoized_property
  146. def _mysqlconnector_version_info(self):
  147. if self.dbapi and hasattr(self.dbapi, "__version__"):
  148. m = re.match(r"(\d+)\.(\d+)(?:\.(\d+))?", self.dbapi.__version__)
  149. if m:
  150. return tuple(int(x) for x in m.group(1, 2, 3) if x is not None)
  151. @util.memoized_property
  152. def _mysqlconnector_double_percents(self):
  153. return not util.py3k and self._mysqlconnector_version_info < (2, 0)
  154. def _detect_charset(self, connection):
  155. return connection.connection.charset
  156. def _extract_error_code(self, exception):
  157. return exception.errno
  158. def is_disconnect(self, e, connection, cursor):
  159. errnos = (2006, 2013, 2014, 2045, 2055, 2048)
  160. exceptions = (self.dbapi.OperationalError, self.dbapi.InterfaceError)
  161. if isinstance(e, exceptions):
  162. return (
  163. e.errno in errnos
  164. or "MySQL Connection not available." in str(e)
  165. or "Connection to MySQL is not available" in str(e)
  166. )
  167. else:
  168. return False
  169. def _compat_fetchall(self, rp, charset=None):
  170. return rp.fetchall()
  171. def _compat_fetchone(self, rp, charset=None):
  172. return rp.fetchone()
  173. _isolation_lookup = set(
  174. [
  175. "SERIALIZABLE",
  176. "READ UNCOMMITTED",
  177. "READ COMMITTED",
  178. "REPEATABLE READ",
  179. "AUTOCOMMIT",
  180. ]
  181. )
  182. def _set_isolation_level(self, connection, level):
  183. if level == "AUTOCOMMIT":
  184. connection.autocommit = True
  185. else:
  186. connection.autocommit = False
  187. super(MySQLDialect_mysqlconnector, self)._set_isolation_level(
  188. connection, level
  189. )
  190. dialect = MySQLDialect_mysqlconnector