Skip to content

Commit 4b664e8

Browse files
authored
Fix TypeError by patching register_default_jsonb from psycopg2 (#350)
1 parent 6e17021 commit 4b664e8

File tree

2 files changed

+33
-3
lines changed

2 files changed

+33
-3
lines changed

aws_xray_sdk/ext/psycopg2/patch.py

+19-3
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77

88

99
def patch():
10-
1110
wrapt.wrap_function_wrapper(
1211
'psycopg2',
1312
'connect',
@@ -24,11 +23,16 @@ def patch():
2423
_xray_register_type_fix
2524
)
2625

26+
wrapt.wrap_function_wrapper(
27+
'psycopg2.extras',
28+
'register_default_jsonb',
29+
_xray_register_default_jsonb_fix
30+
)
2731

28-
def _xray_traced_connect(wrapped, instance, args, kwargs):
2932

33+
def _xray_traced_connect(wrapped, instance, args, kwargs):
3034
conn = wrapped(*args, **kwargs)
31-
parameterized_dsn = { c[0]: c[-1] for c in map(methodcaller('split', '='), conn.dsn.split(' '))}
35+
parameterized_dsn = {c[0]: c[-1] for c in map(methodcaller('split', '='), conn.dsn.split(' '))}
3236
meta = {
3337
'database_type': 'PostgreSQL',
3438
'url': 'postgresql://{}@{}:{}/{}'.format(
@@ -44,10 +48,22 @@ def _xray_traced_connect(wrapped, instance, args, kwargs):
4448

4549
return XRayTracedConn(conn, meta)
4650

51+
4752
def _xray_register_type_fix(wrapped, instance, args, kwargs):
4853
"""Send the actual connection or curser to register type."""
4954
our_args = list(copy.copy(args))
5055
if len(our_args) == 2 and isinstance(our_args[1], (XRayTracedConn, XRayTracedCursor)):
5156
our_args[1] = our_args[1].__wrapped__
5257

5358
return wrapped(*our_args, **kwargs)
59+
60+
61+
def _xray_register_default_jsonb_fix(wrapped, instance, args, kwargs):
62+
our_kwargs = dict()
63+
for key, value in kwargs.items():
64+
if key == "conn_or_curs" and isinstance(value, (XRayTracedConn, XRayTracedCursor)):
65+
# unwrap the connection or cursor to be sent to register_default_jsonb
66+
value = value.__wrapped__
67+
our_kwargs[key] = value
68+
69+
return wrapped(*args, **our_kwargs)

tests/ext/psycopg2/test_psycopg2.py

+14
Original file line numberDiff line numberDiff line change
@@ -173,3 +173,17 @@ def test_query_as_string():
173173
test_sql = psycopg2.sql.Identifier('test')
174174
assert test_sql.as_string(conn)
175175
assert test_sql.as_string(conn.cursor())
176+
177+
178+
def test_register_default_jsonb():
179+
with testing.postgresql.Postgresql() as postgresql:
180+
url = postgresql.url()
181+
dsn = postgresql.dsn()
182+
conn = psycopg2.connect('dbname=' + dsn['database'] +
183+
' password=mypassword' +
184+
' host=' + dsn['host'] +
185+
' port=' + str(dsn['port']) +
186+
' user=' + dsn['user'])
187+
188+
assert psycopg2.extras.register_default_jsonb(conn_or_curs=conn, loads=lambda x: x)
189+
assert psycopg2.extras.register_default_jsonb(conn_or_curs=conn.cursor(), loads=lambda x: x)

0 commit comments

Comments
 (0)