Skip to content
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

Cursors as context managers #99

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open

Conversation

onnokort
Copy link

Hi,

I think it would be great if cursors could be used as context managers as well. They acquire a limiting resource: Read locks on the database file. In a multi-threaded or multi-process situation, it is important to not rely on (unreliable) garbage collection to mop up any old, open, unused cursors. In such a case, it is easy to end up with 'OperationalError: database is locked' errors on any process attempting to write.

This adds code to use cursors as context managers, like there is already for connections. Included is a simple test case (passes fine on python 2.7.6) and documentation of these methods.

But as a further suggestion, the docs might become more helpful if they would state this problem more clearly. Currently, the code examples do not deal with this problem and implicitly suggest the assumption that Python's garbage collection is sufficient and so implicitly assume a read-only or a single-threaded use-case of pysqlite.

This adds methods __enter__ and __exit__ to a cursor, providing it with
context manager functionality. Leaving a cursor context will close the
cursor.

It is important to close cursors in a multi-threaded or multi-process
SQLite situation with writers present, as open cursors will keep read
locks on the database and timely garbage-collection cannot be counted
on.
This adds a simple test of cursors as context managers to the test suite.
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.

None yet

1 participant