Skip to content

Commit

Permalink
dbapi2 patching: do respect with statement on cursor objects (aws#17)
Browse files Browse the repository at this point in the history
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`).
  • Loading branch information
MarSoft authored and haotianw465 committed Jan 19, 2018
1 parent 9584a25 commit 0b00e4b
Showing 1 changed file with 7 additions and 0 deletions.
7 changes: 7 additions & 0 deletions aws_xray_sdk/ext/dbapi2.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,13 @@ def __init__(self, cursor, meta={}):
db_type = cursor.__class__.__module__.split('.')[0]
self._xray_meta['database_type'] = db_type

def __enter__(self):

value = self.__wrapped__.__enter__()
if value is not self.__wrapped__:
return value
return self

@xray_recorder.capture()
def execute(self, query, *args, **kwargs):

Expand Down

0 comments on commit 0b00e4b

Please sign in to comment.