diff --git a/psycopg/adapter_binary.c b/psycopg/adapter_binary.c index dcff6ca6..75cfa1c0 100644 --- a/psycopg/adapter_binary.c +++ b/psycopg/adapter_binary.c @@ -137,10 +137,8 @@ binary_quote(binaryObject *self) int buffer_len; size_t len = 0; - if (self->buffer == NULL) - self->buffer = PyString_FromString(""); /* if we got a plain string or a buffer we escape it and save the buffer */ - else if (PyString_Check(self->wrapped) || PyBuffer_Check(self->wrapped)) { + if (PyString_Check(self->wrapped) || PyBuffer_Check(self->wrapped)) { /* escape and build quoted buffer */ PyObject_AsCharBuffer(self->wrapped, &buffer, &buffer_len); @@ -151,8 +149,14 @@ binary_quote(binaryObject *self) return NULL; } - self->buffer = PyString_FromFormat("'%s'", to); - PQfreemem(to); + if (len > 0) { + self->buffer = PyString_FromFormat("'%s'", to); + PQfreemem(to); + } + else { + self->buffer = PyString_FromString("''"); + PQfreemem(to); + } } /* if the wrapped object is not a string or a buffer, this is an error */ diff --git a/tests/types_basic.py b/tests/types_basic.py index 8a867df0..446ad153 100644 --- a/tests/types_basic.py +++ b/tests/types_basic.py @@ -62,9 +62,9 @@ class TypesBasicTests(TestCase): b = psycopg2.Binary(s) r = str(self.execute("SELECT %s::bytea AS foo", (b,))) self.failUnless(r == s, "wrong binary quoting") - + # test to make sure an empty Binary is converted to an empty string b = psycopg2.Binary('') - self.assertEqual(str(b), '') + self.assertEqual(str(b), "''") def testArray(self): s = self.execute("SELECT %s AS foo", ([[1,2],[3,4]],))