1# mysql/pymysql.py 2# Copyright (C) 2005-2021 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: http://www.opensource.org/licenses/mit-license.php 7 8r""" 9 10.. dialect:: mysql+pymysql 11 :name: PyMySQL 12 :dbapi: pymysql 13 :connectstring: mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>] 14 :url: https://pymysql.readthedocs.io/ 15 16Unicode 17------- 18 19Please see :ref:`mysql_unicode` for current recommendations on unicode 20handling. 21 22MySQL-Python Compatibility 23-------------------------- 24 25The pymysql DBAPI is a pure Python port of the MySQL-python (MySQLdb) driver, 26and targets 100% compatibility. Most behavioral notes for MySQL-python apply 27to the pymysql driver as well. 28 29""" # noqa 30 31from .mysqldb import MySQLDialect_mysqldb 32from ...util import langhelpers 33from ...util import py3k 34 35 36class MySQLDialect_pymysql(MySQLDialect_mysqldb): 37 driver = "pymysql" 38 39 description_encoding = None 40 41 # generally, these two values should be both True 42 # or both False. PyMySQL unicode tests pass all the way back 43 # to 0.4 either way. See [ticket:3337] 44 supports_unicode_statements = True 45 supports_unicode_binds = True 46 47 def __init__(self, server_side_cursors=False, **kwargs): 48 super(MySQLDialect_pymysql, self).__init__(**kwargs) 49 self.server_side_cursors = server_side_cursors 50 51 @langhelpers.memoized_property 52 def supports_server_side_cursors(self): 53 try: 54 cursors = __import__("pymysql.cursors").cursors 55 self._sscursor = cursors.SSCursor 56 return True 57 except (ImportError, AttributeError): 58 return False 59 60 @classmethod 61 def dbapi(cls): 62 return __import__("pymysql") 63 64 def create_connect_args(self, url, _translate_args=None): 65 if _translate_args is None: 66 _translate_args = dict(username="user") 67 return super(MySQLDialect_pymysql, self).create_connect_args( 68 url, _translate_args=_translate_args 69 ) 70 71 def is_disconnect(self, e, connection, cursor): 72 if super(MySQLDialect_pymysql, self).is_disconnect( 73 e, connection, cursor 74 ): 75 return True 76 elif isinstance(e, self.dbapi.Error): 77 str_e = str(e).lower() 78 return ( 79 "already closed" in str_e or "connection was killed" in str_e 80 ) 81 else: 82 return False 83 84 if py3k: 85 86 def _extract_error_code(self, exception): 87 if isinstance(exception.args[0], Exception): 88 exception = exception.args[0] 89 return exception.args[0] 90 91 92dialect = MySQLDialect_pymysql 93