mysqldb.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. # dialects/mysql/mysqldb.py
  2. # Copyright (C) 2005-2024 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. # mypy: ignore-errors
  8. """
  9. .. dialect:: mysql+mysqldb
  10. :name: mysqlclient (maintained fork of MySQL-Python)
  11. :dbapi: mysqldb
  12. :connectstring: mysql+mysqldb://<user>:<password>@<host>[:<port>]/<dbname>
  13. :url: https://pypi.org/project/mysqlclient/
  14. Driver Status
  15. -------------
  16. The mysqlclient DBAPI is a maintained fork of the
  17. `MySQL-Python <https://sourceforge.net/projects/mysql-python>`_ DBAPI
  18. that is no longer maintained. `mysqlclient`_ supports Python 2 and Python 3
  19. and is very stable.
  20. .. _mysqlclient: https://github.com/PyMySQL/mysqlclient-python
  21. .. _mysqldb_unicode:
  22. Unicode
  23. -------
  24. Please see :ref:`mysql_unicode` for current recommendations on unicode
  25. handling.
  26. .. _mysqldb_ssl:
  27. SSL Connections
  28. ----------------
  29. The mysqlclient and PyMySQL DBAPIs accept an additional dictionary under the
  30. key "ssl", which may be specified using the
  31. :paramref:`_sa.create_engine.connect_args` dictionary::
  32. engine = create_engine(
  33. "mysql+mysqldb://scott:tiger@192.168.0.134/test",
  34. connect_args={
  35. "ssl": {
  36. "ca": "/home/gord/client-ssl/ca.pem",
  37. "cert": "/home/gord/client-ssl/client-cert.pem",
  38. "key": "/home/gord/client-ssl/client-key.pem"
  39. }
  40. }
  41. )
  42. For convenience, the following keys may also be specified inline within the URL
  43. where they will be interpreted into the "ssl" dictionary automatically:
  44. "ssl_ca", "ssl_cert", "ssl_key", "ssl_capath", "ssl_cipher",
  45. "ssl_check_hostname". An example is as follows::
  46. connection_uri = (
  47. "mysql+mysqldb://scott:tiger@192.168.0.134/test"
  48. "?ssl_ca=/home/gord/client-ssl/ca.pem"
  49. "&ssl_cert=/home/gord/client-ssl/client-cert.pem"
  50. "&ssl_key=/home/gord/client-ssl/client-key.pem"
  51. )
  52. .. seealso::
  53. :ref:`pymysql_ssl` in the PyMySQL dialect
  54. Using MySQLdb with Google Cloud SQL
  55. -----------------------------------
  56. Google Cloud SQL now recommends use of the MySQLdb dialect. Connect
  57. using a URL like the following::
  58. mysql+mysqldb://root@/<dbname>?unix_socket=/cloudsql/<projectid>:<instancename>
  59. Server Side Cursors
  60. -------------------
  61. The mysqldb dialect supports server-side cursors. See :ref:`mysql_ss_cursors`.
  62. """
  63. import re
  64. from .base import MySQLCompiler
  65. from .base import MySQLDialect
  66. from .base import MySQLExecutionContext
  67. from .base import MySQLIdentifierPreparer
  68. from .base import TEXT
  69. from ... import sql
  70. from ... import util
  71. class MySQLExecutionContext_mysqldb(MySQLExecutionContext):
  72. @property
  73. def rowcount(self):
  74. if hasattr(self, "_rowcount"):
  75. return self._rowcount
  76. else:
  77. return self.cursor.rowcount
  78. class MySQLCompiler_mysqldb(MySQLCompiler):
  79. pass
  80. class MySQLDialect_mysqldb(MySQLDialect):
  81. driver = "mysqldb"
  82. supports_statement_cache = True
  83. supports_unicode_statements = True
  84. supports_sane_rowcount = True
  85. supports_sane_multi_rowcount = True
  86. supports_native_decimal = True
  87. default_paramstyle = "format"
  88. execution_ctx_cls = MySQLExecutionContext_mysqldb
  89. statement_compiler = MySQLCompiler_mysqldb
  90. preparer = MySQLIdentifierPreparer
  91. def __init__(self, **kwargs):
  92. super().__init__(**kwargs)
  93. self._mysql_dbapi_version = (
  94. self._parse_dbapi_version(self.dbapi.__version__)
  95. if self.dbapi is not None and hasattr(self.dbapi, "__version__")
  96. else (0, 0, 0)
  97. )
  98. def _parse_dbapi_version(self, version):
  99. m = re.match(r"(\d+)\.(\d+)(?:\.(\d+))?", version)
  100. if m:
  101. return tuple(int(x) for x in m.group(1, 2, 3) if x is not None)
  102. else:
  103. return (0, 0, 0)
  104. @util.langhelpers.memoized_property
  105. def supports_server_side_cursors(self):
  106. try:
  107. cursors = __import__("MySQLdb.cursors").cursors
  108. self._sscursor = cursors.SSCursor
  109. return True
  110. except (ImportError, AttributeError):
  111. return False
  112. @classmethod
  113. def import_dbapi(cls):
  114. return __import__("MySQLdb")
  115. def on_connect(self):
  116. super_ = super().on_connect()
  117. def on_connect(conn):
  118. if super_ is not None:
  119. super_(conn)
  120. charset_name = conn.character_set_name()
  121. if charset_name is not None:
  122. cursor = conn.cursor()
  123. cursor.execute("SET NAMES %s" % charset_name)
  124. cursor.close()
  125. return on_connect
  126. def do_ping(self, dbapi_connection):
  127. dbapi_connection.ping()
  128. return True
  129. def do_executemany(self, cursor, statement, parameters, context=None):
  130. rowcount = cursor.executemany(statement, parameters)
  131. if context is not None:
  132. context._rowcount = rowcount
  133. def _check_unicode_returns(self, connection):
  134. # work around issue fixed in
  135. # https://github.com/farcepest/MySQLdb1/commit/cd44524fef63bd3fcb71947392326e9742d520e8
  136. # specific issue w/ the utf8mb4_bin collation and unicode returns
  137. collation = connection.exec_driver_sql(
  138. "show collation where %s = 'utf8mb4' and %s = 'utf8mb4_bin'"
  139. % (
  140. self.identifier_preparer.quote("Charset"),
  141. self.identifier_preparer.quote("Collation"),
  142. )
  143. ).scalar()
  144. has_utf8mb4_bin = self.server_version_info > (5,) and collation
  145. if has_utf8mb4_bin:
  146. additional_tests = [
  147. sql.collate(
  148. sql.cast(
  149. sql.literal_column("'test collated returns'"),
  150. TEXT(charset="utf8mb4"),
  151. ),
  152. "utf8mb4_bin",
  153. )
  154. ]
  155. else:
  156. additional_tests = []
  157. return super()._check_unicode_returns(connection, additional_tests)
  158. def create_connect_args(self, url, _translate_args=None):
  159. if _translate_args is None:
  160. _translate_args = dict(
  161. database="db", username="user", password="passwd"
  162. )
  163. opts = url.translate_connect_args(**_translate_args)
  164. opts.update(url.query)
  165. util.coerce_kw_type(opts, "compress", bool)
  166. util.coerce_kw_type(opts, "connect_timeout", int)
  167. util.coerce_kw_type(opts, "read_timeout", int)
  168. util.coerce_kw_type(opts, "write_timeout", int)
  169. util.coerce_kw_type(opts, "client_flag", int)
  170. util.coerce_kw_type(opts, "local_infile", int)
  171. # Note: using either of the below will cause all strings to be
  172. # returned as Unicode, both in raw SQL operations and with column
  173. # types like String and MSString.
  174. util.coerce_kw_type(opts, "use_unicode", bool)
  175. util.coerce_kw_type(opts, "charset", str)
  176. # Rich values 'cursorclass' and 'conv' are not supported via
  177. # query string.
  178. ssl = {}
  179. keys = [
  180. ("ssl_ca", str),
  181. ("ssl_key", str),
  182. ("ssl_cert", str),
  183. ("ssl_capath", str),
  184. ("ssl_cipher", str),
  185. ("ssl_check_hostname", bool),
  186. ]
  187. for key, kw_type in keys:
  188. if key in opts:
  189. ssl[key[4:]] = opts[key]
  190. util.coerce_kw_type(ssl, key[4:], kw_type)
  191. del opts[key]
  192. if ssl:
  193. opts["ssl"] = ssl
  194. # FOUND_ROWS must be set in CLIENT_FLAGS to enable
  195. # supports_sane_rowcount.
  196. client_flag = opts.get("client_flag", 0)
  197. client_flag_found_rows = self._found_rows_client_flag()
  198. if client_flag_found_rows is not None:
  199. client_flag |= client_flag_found_rows
  200. opts["client_flag"] = client_flag
  201. return [[], opts]
  202. def _found_rows_client_flag(self):
  203. if self.dbapi is not None:
  204. try:
  205. CLIENT_FLAGS = __import__(
  206. self.dbapi.__name__ + ".constants.CLIENT"
  207. ).constants.CLIENT
  208. except (AttributeError, ImportError):
  209. return None
  210. else:
  211. return CLIENT_FLAGS.FOUND_ROWS
  212. else:
  213. return None
  214. def _extract_error_code(self, exception):
  215. return exception.args[0]
  216. def _detect_charset(self, connection):
  217. """Sniff out the character set in use for connection results."""
  218. try:
  219. # note: the SQL here would be
  220. # "SHOW VARIABLES LIKE 'character_set%%'"
  221. cset_name = connection.connection.character_set_name
  222. except AttributeError:
  223. util.warn(
  224. "No 'character_set_name' can be detected with "
  225. "this MySQL-Python version; "
  226. "please upgrade to a recent version of MySQL-Python. "
  227. "Assuming latin1."
  228. )
  229. return "latin1"
  230. else:
  231. return cset_name()
  232. def get_isolation_level_values(self, dbapi_connection):
  233. return (
  234. "SERIALIZABLE",
  235. "READ UNCOMMITTED",
  236. "READ COMMITTED",
  237. "REPEATABLE READ",
  238. "AUTOCOMMIT",
  239. )
  240. def set_isolation_level(self, dbapi_connection, level):
  241. if level == "AUTOCOMMIT":
  242. dbapi_connection.autocommit(True)
  243. else:
  244. dbapi_connection.autocommit(False)
  245. super().set_isolation_level(dbapi_connection, level)
  246. dialect = MySQLDialect_mysqldb