aiosqlite icon indicating copy to clipboard operation
aiosqlite copied to clipboard

Context manager behaviour is different to the sqlite3 module

Open tmewett opened this issue 4 years ago • 0 comments
trafficstars

Description

A minor point that lead to a little confusion.

sqlite3's Connection's context manager is documented as handling committing and rolling back of transactions:

https://docs.python.org/3.9/library/sqlite3.html#using-the-connection-as-a-context-manager

import sqlite3

con = sqlite3.connect(":memory:")
con.execute("create table person (id integer primary key, firstname varchar unique)")

# Successful, con.commit() is called automatically afterwards
with con:
    con.execute("insert into person(firstname) values (?)", ("Joe",))

# Connection object used as context manager only commits or rollbacks transactions,
# so the connection object should be closed manually
con.close()

However aiosqlite seems to have the Connection context manager handle the opening and closing of the DB connection. In my usage, I notice that when exiting this manager, the transactions are not committed.

Possible solutions

I think at least some documentation about the current behaviour of the context managers would be a great improvement.

If we wanted to alter the behaviour, perhaps aisqlite.connect could return a new wrapper Connector class. Awaiting a Connector returns an active Connection, and async with manages closing it. Then the async with behaviour of the Connection itself is changed to handle transactions, as described.

Details

  • OS: Debian 10 buster
  • Python version: 3.7.3
  • aiosqlite version: 0.17.0

tmewett avatar Apr 06 '21 13:04 tmewett