Skip to content

Commit 0b00e4b

Browse files
MarSofthaotianw465
authored andcommitted
dbapi2 patching: do respect with statement on cursor objects (#17)
Some database backends (including already-supported `django` and not-yet-supported `psycopg2`) implement non-standard ability to use cursor in `with` statement like this: conn = get_db_connection() with conn.cursor() as cur: cur.execute('MY QUERY') This syntax will automatically close cursor when leaving `with` statement. The problem is that `Cursor.__enter__` returns `self`, thus dropping our `XRayTracedCursor` wrapper. This PR aims to fix that issue by wrapping `__enter__` as well. If connection's `__enter__` returned itself then we return wrapper instead, else we return what cursor returned for compatibility. Probably something similar should also be implemented for `Connection.__enter__` because some backends support it as well (including `sqlite3`).
1 parent 9584a25 commit 0b00e4b

File tree

1 file changed

+7
-0
lines changed

1 file changed

+7
-0
lines changed

aws_xray_sdk/ext/dbapi2.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,13 @@ def __init__(self, cursor, meta={}):
3333
db_type = cursor.__class__.__module__.split('.')[0]
3434
self._xray_meta['database_type'] = db_type
3535

36+
def __enter__(self):
37+
38+
value = self.__wrapped__.__enter__()
39+
if value is not self.__wrapped__:
40+
return value
41+
return self
42+
3643
@xray_recorder.capture()
3744
def execute(self, query, *args, **kwargs):
3845

0 commit comments

Comments
 (0)