Support sqlite3.connect(autocommit=True) connections

Database() now accepts connections created with the Python 3.12+
autocommit=True option. The library manages transactions itself using
explicit BEGIN/COMMIT/ROLLBACK and savepoint statements, all guarded by
conn.in_transaction, so it behaves identically in driver-level
autocommit mode - the entire test suite passes under
pytest --sqlite-autocommit with no further changes.

autocommit=False connections are still rejected with TransactionError:
in that mode the driver holds an implicit transaction open at all
times, so explicit BEGIN fails and PRAGMA journal_mode cannot run.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PFkrS2nuP8mo1jmT594VCd
This commit is contained in:
Claude 2026-07-09 05:19:01 +00:00
commit 887c6543ee
No known key found for this signature in database
5 changed files with 78 additions and 19 deletions

View file

@ -557,17 +557,16 @@ class Database:
if recreate:
raise ValueError("recreate cannot be used with connections, only paths")
self.conn = cast(sqlite3.Connection, filename_or_conn)
# Python 3.12+ autocommit=True/False connections make commit()
# and rollback() behave differently, silently breaking the
# transaction handling used by every write method
autocommit = getattr(self.conn, "autocommit", None)
if autocommit is not None and autocommit != getattr(
sqlite3, "LEGACY_TRANSACTION_CONTROL", -1
):
# Python 3.12+ autocommit=False connections hold an implicit
# transaction open at all times, which breaks the explicit
# BEGIN/COMMIT transaction handling used by every write method.
# autocommit=True connections work fine - the library manages
# transactions itself with explicit SQL statements
if getattr(self.conn, "autocommit", None) is False:
raise TransactionError(
"sqlite-utils requires a connection that uses the default "
"transaction handling - connections created with "
"autocommit=True or autocommit=False are not supported"
"sqlite-utils does not support connections created with "
"autocommit=False - use autocommit=True or the default "
"transaction handling instead"
)
self._tracer: Optional[Tracer] = tracer
if recursive_triggers: