From 8ebc3ebffcd5d06ae9edc6d80a6e943d3499ea14 Mon Sep 17 00:00:00 2001 From: Gord Thompson Date: Sun, 20 Oct 2019 11:04:51 -0400 Subject: [PATCH] add on_connect to MySQLDialect_pyodbc Fixes: #4876 ### Description add on_connect to MySQLDialect_pyodbc to specify Unicode encoding/decoding settings for the pyodbc connection ### Checklist This pull request is: - [ ] A documentation / typographical error fix - Good to go, no issue or tests are needed - [x] A short code fix - please include the issue number, and create an issue if none exists, which must include a complete example of the issue. one line code fixes without an issue and demonstration will not be accepted. - Please include: `Fixes: #` in the commit message - please include tests. one line code fixes without tests will not be accepted. - [ ] A new feature implementation - please include the issue number, and create an issue if none exists, which must include a complete example of how the feature would look. - Please include: `Fixes: #` in the commit message - please include tests. **Have a nice day!** Closes: #4885 Pull-request: https://github.com/sqlalchemy/sqlalchemy/pull/4885 Pull-request-sha: 58f6176331702b72f3ea8342c93be6fe9a3db26f Change-Id: If05c1cf8fb1d8efebcf809bdefe40242118d763f --- lib/sqlalchemy/dialects/mysql/pyodbc.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/lib/sqlalchemy/dialects/mysql/pyodbc.py b/lib/sqlalchemy/dialects/mysql/pyodbc.py index 6866c3f42f..9a18b50904 100644 --- a/lib/sqlalchemy/dialects/mysql/pyodbc.py +++ b/lib/sqlalchemy/dialects/mysql/pyodbc.py @@ -23,6 +23,7 @@ """ import re +import sys from .base import MySQLDialect from .base import MySQLExecutionContext @@ -86,5 +87,28 @@ class MySQLDialect_pyodbc(PyODBCConnector, MySQLDialect): else: return None + def on_connect(self): + super_ = super(MySQLDialect_pyodbc, self).on_connect() + + def on_connect(conn): + if super_ is not None: + super_(conn) + + # declare Unicode encoding for pyodbc as per + # https://github.com/mkleehammer/pyodbc/wiki/Unicode + pyodbc_SQL_CHAR = 1 # pyodbc.SQL_CHAR + pyodbc_SQL_WCHAR = -8 # pyodbc.SQL_WCHAR + if sys.version_info.major > 2: + conn.setdecoding(pyodbc_SQL_CHAR, encoding='utf-8') + conn.setdecoding(pyodbc_SQL_WCHAR, encoding='utf-8') + conn.setencoding(encoding='utf-8') + else: + conn.setdecoding(pyodbc_SQL_CHAR, encoding='utf-8') + conn.setdecoding(pyodbc_SQL_WCHAR, encoding='utf-8') + conn.setencoding(str, encoding='utf-8') + conn.setencoding(unicode, encoding='utf-8') + + return on_connect + dialect = MySQLDialect_pyodbc -- 2.47.2