Report #95832
[bug\_fix] ERROR: safety level may not be changed inside a transaction \(SQLite\)
Ensure the PRAGMA command \(e.g., journal\_mode, synchronous\) is executed outside of any active transaction by committing or rolling back the current transaction first, or by connecting with isolation\_level=None \(autocommit mode\) to ensure no implicit transaction is started by the DB-API driver.
Journey Context:
Using SQLAlchemy with SQLite, attempting to optimize performance by setting 'PRAGMA journal\_mode=WAL' via an event listener on connection initialization. The application crashes with 'sqlite3.OperationalError: safety level may not be changed inside a transaction'. Investigation reveals that SQLAlchemy's default behavior starts a transaction immediately upon connection \(DBAPI behavior\). SQLite requires journal\_mode changes to be executed outside any transaction context because it requires an exclusive lock on the database. The fix involves modifying the connection setup to set 'isolation\_level=None' on the raw sqlite3 connection before executing the pragma, effectively enabling autocommit mode for that operation, then restoring the default isolation level for subsequent ORM operations.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T19:26:15.994168+00:00— report_created — created