Added Json.prepare()

Close #562
This commit is contained in:
Daniele Varrazzo 2017-06-16 01:37:49 +01:00
parent 21ee8b62ef
commit 789eb64f3a
3 changed files with 28 additions and 1 deletions

2
NEWS
View File

@ -21,6 +21,8 @@ What's new in psycopg 2.7.2
- Fixed `~psycopg2.extras.ReplicationCursor.consume_stream()` - Fixed `~psycopg2.extras.ReplicationCursor.consume_stream()`
*keepalive_interval* argument (:ticket:`#547`). *keepalive_interval* argument (:ticket:`#547`).
- Fixed random `!SystemError` upon receiving abort signal (:ticket:`#551`). - Fixed random `!SystemError` upon receiving abort signal (:ticket:`#551`).
- Added `~psycopg2.extras.Json` `!prepare()` method to consider connection
params when adapting (:ticket:`#562`).
- `~psycopg2.errorcodes` map updated to PostgreSQL 10 beta 1. - `~psycopg2.errorcodes` map updated to PostgreSQL 10 beta 1.

View File

@ -66,6 +66,7 @@ class Json(object):
""" """
def __init__(self, adapted, dumps=None): def __init__(self, adapted, dumps=None):
self.adapted = adapted self.adapted = adapted
self._conn = None
if dumps is not None: if dumps is not None:
self._dumps = dumps self._dumps = dumps
@ -93,9 +94,15 @@ class Json(object):
"json module not available: " "json module not available: "
"you should provide a dumps function") "you should provide a dumps function")
def prepare(self, conn):
self._conn = conn
def getquoted(self): def getquoted(self):
s = self.dumps(self.adapted) s = self.dumps(self.adapted)
return QuotedString(s).getquoted() qs = QuotedString(s)
if self._conn is not None:
qs.prepare(self._conn)
return qs.getquoted()
if sys.version_info < (3,): if sys.version_info < (3,):
def __str__(self): def __str__(self):

View File

@ -1084,6 +1084,24 @@ class JsonTestCase(ConnectingTestCase):
self.assert_(s.startswith("'")) self.assert_(s.startswith("'"))
self.assert_(s.endswith("'")) self.assert_(s.endswith("'"))
@skip_if_no_json_module
def test_scs(self):
cnn_on = self.connect(options="-c standard_conforming_strings=on")
cur_on = cnn_on.cursor()
self.assertEqual(
cur_on.mogrify("%s", [psycopg2.extras.Json({'a': '"'})]),
b'\'{"a": "\\""}\'')
cnn_off = self.connect(options="-c standard_conforming_strings=off")
cur_off = cnn_off.cursor()
self.assertEqual(
cur_off.mogrify("%s", [psycopg2.extras.Json({'a': '"'})]),
b'E\'{"a": "\\\\""}\'')
self.assertEqual(
cur_on.mogrify("%s", [psycopg2.extras.Json({'a': '"'})]),
b'\'{"a": "\\""}\'')
def skip_if_no_jsonb_type(f): def skip_if_no_jsonb_type(f):
return skip_before_postgres(9, 4)(f) return skip_before_postgres(9, 4)(f)