pymysql.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. # dialects/mysql/pymysql.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. r"""
  8. .. dialect:: mysql+pymysql
  9. :name: PyMySQL
  10. :dbapi: pymysql
  11. :connectstring: mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]
  12. :url: https://pymysql.readthedocs.io/
  13. Unicode
  14. -------
  15. Please see :ref:`mysql_unicode` for current recommendations on unicode
  16. handling.
  17. .. _pymysql_ssl:
  18. SSL Connections
  19. ------------------
  20. The PyMySQL DBAPI accepts the same SSL arguments as that of MySQLdb,
  21. described at :ref:`mysqldb_ssl`. See that section for additional examples.
  22. If the server uses an automatically-generated certificate that is self-signed
  23. or does not match the host name (as seen from the client), it may also be
  24. necessary to indicate ``ssl_check_hostname=false`` in PyMySQL::
  25. connection_uri = (
  26. "mysql+pymysql://scott:tiger@192.168.0.134/test"
  27. "?ssl_ca=/home/gord/client-ssl/ca.pem"
  28. "&ssl_cert=/home/gord/client-ssl/client-cert.pem"
  29. "&ssl_key=/home/gord/client-ssl/client-key.pem"
  30. "&ssl_check_hostname=false"
  31. )
  32. MySQL-Python Compatibility
  33. --------------------------
  34. The pymysql DBAPI is a pure Python port of the MySQL-python (MySQLdb) driver,
  35. and targets 100% compatibility. Most behavioral notes for MySQL-python apply
  36. to the pymysql driver as well.
  37. """ # noqa
  38. from .mysqldb import MySQLDialect_mysqldb
  39. from ...util import langhelpers
  40. from ...util import py3k
  41. class MySQLDialect_pymysql(MySQLDialect_mysqldb):
  42. driver = "pymysql"
  43. supports_statement_cache = True
  44. description_encoding = None
  45. # generally, these two values should be both True
  46. # or both False. PyMySQL unicode tests pass all the way back
  47. # to 0.4 either way. See [ticket:3337]
  48. supports_unicode_statements = True
  49. supports_unicode_binds = True
  50. @langhelpers.memoized_property
  51. def supports_server_side_cursors(self):
  52. try:
  53. cursors = __import__("pymysql.cursors").cursors
  54. self._sscursor = cursors.SSCursor
  55. return True
  56. except (ImportError, AttributeError):
  57. return False
  58. @classmethod
  59. def dbapi(cls):
  60. return __import__("pymysql")
  61. @langhelpers.memoized_property
  62. def _send_false_to_ping(self):
  63. """determine if pymysql has deprecated, changed the default of,
  64. or removed the 'reconnect' argument of connection.ping().
  65. See #10492 and
  66. https://github.com/PyMySQL/mysqlclient/discussions/651#discussioncomment-7308971
  67. for background.
  68. """ # noqa: E501
  69. try:
  70. Connection = __import__(
  71. "pymysql.connections"
  72. ).connections.Connection
  73. except (ImportError, AttributeError):
  74. return True
  75. else:
  76. insp = langhelpers.get_callable_argspec(Connection.ping)
  77. try:
  78. reconnect_arg = insp.args[1]
  79. except IndexError:
  80. return False
  81. else:
  82. return reconnect_arg == "reconnect" and (
  83. not insp.defaults or insp.defaults[0] is not False
  84. )
  85. def _ping_impl(self, dbapi_connection):
  86. if self._send_false_to_ping:
  87. dbapi_connection.ping(False)
  88. else:
  89. dbapi_connection.ping()
  90. return True
  91. def create_connect_args(self, url, _translate_args=None):
  92. if _translate_args is None:
  93. _translate_args = dict(username="user")
  94. return super(MySQLDialect_pymysql, self).create_connect_args(
  95. url, _translate_args=_translate_args
  96. )
  97. def is_disconnect(self, e, connection, cursor):
  98. if super(MySQLDialect_pymysql, self).is_disconnect(
  99. e, connection, cursor
  100. ):
  101. return True
  102. elif isinstance(e, self.dbapi.Error):
  103. str_e = str(e).lower()
  104. return (
  105. "already closed" in str_e or "connection was killed" in str_e
  106. )
  107. else:
  108. return False
  109. if py3k:
  110. def _extract_error_code(self, exception):
  111. if isinstance(exception.args[0], Exception):
  112. exception = exception.args[0]
  113. return exception.args[0]
  114. dialect = MySQLDialect_pymysql