Skip to content

dbapi2 patching: do respect with statement on cursor objects #17

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 19, 2018

Conversation

MarSoft
Copy link
Contributor

@MarSoft MarSoft commented Jan 19, 2018

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).

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`).
@haotianw465 haotianw465 merged commit 0b00e4b into aws:master Jan 19, 2018
@MarSoft MarSoft deleted the patch-1 branch March 18, 2018 22:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants