From 61764ea581d499acd6d9d59455579d3da8d76447 Mon Sep 17 00:00:00 2001 From: Daniele Varrazzo Date: Fri, 1 Jul 2016 19:11:04 +0100 Subject: [PATCH] Allow adapting bytes using QuotedString on Python 3 too Close #365. --- NEWS | 1 + psycopg/adapter_qstring.c | 6 ++---- tests/test_quote.py | 9 +++++++++ 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/NEWS b/NEWS index 55bcd671..da8e53f7 100644 --- a/NEWS +++ b/NEWS @@ -13,6 +13,7 @@ What's new in psycopg 2.6.2 (:ticket:`#333`). - Fixed `!PersistentConnectionPool` on Python 3 (:ticket:`#348`). - Fixed segfault on `repr()` of an unitialized connection (:ticket:`#361`). +- Allow adapting bytes using QuotedString on Python 3 too (:ticket:`#365`). - Added support for setuptools/wheel (:ticket:`#370`). - Fix build on Windows with Python 3.5, VS 2015 (:ticket:`#380`). - Fixed `!errorcodes.lookup` initialization thread-safety (:ticket:`#382`). diff --git a/psycopg/adapter_qstring.c b/psycopg/adapter_qstring.c index 110093e5..8c5a8f10 100644 --- a/psycopg/adapter_qstring.c +++ b/psycopg/adapter_qstring.c @@ -75,15 +75,13 @@ qstring_quote(qstringObject *self) } } -#if PY_MAJOR_VERSION < 3 - /* if the wrapped object is a simple string, we don't know how to + /* if the wrapped object is a binary string, we don't know how to (re)encode it, so we pass it as-is */ - else if (PyString_Check(self->wrapped)) { + else if (Bytes_Check(self->wrapped)) { str = self->wrapped; /* INCREF to make it ref-wise identical to unicode one */ Py_INCREF(str); } -#endif /* if the wrapped object is not a string, this is an error */ else { diff --git a/tests/test_quote.py b/tests/test_quote.py index e9ab8915..25299e89 100755 --- a/tests/test_quote.py +++ b/tests/test_quote.py @@ -23,6 +23,7 @@ # License for more details. import sys +import testutils from testutils import unittest, ConnectingTestCase import psycopg2 @@ -206,6 +207,14 @@ class TestQuotedString(ConnectingTestCase): self.assertEqual(a.encoding, 'utf_8') self.assertEqual(a.getquoted(), b("'\xe2\x98\x83'")) + @testutils.skip_before_python(3) + def test_adapt_bytes(self): + snowman = u"\u2603" + self.conn.set_client_encoding('utf8') + a = psycopg2.extensions.QuotedString(snowman.encode('utf8')) + a.prepare(self.conn) + self.assertEqual(a.getquoted(), b("'\xe2\x98\x83'")) + def test_suite(): return unittest.TestLoader().loadTestsFromName(__name__)