From: Mike Bayer Date: Thu, 7 Aug 2025 14:48:51 +0000 (-0400) Subject: ensure autocommit is not False for SQLite FK pragma X-Git-Url: http://git.ipfire.org/gitweb/gitweb.cgi?a=commitdiff_plain;p=thirdparty%2Fsqlalchemy%2Fsqlalchemy.git ensure autocommit is not False for SQLite FK pragma References: #12767 References: https://github.com/python/cpython/issues/137205 Change-Id: I6772a4c9c216c6981421043f850cbf833ded2be3 --- diff --git a/lib/sqlalchemy/dialects/sqlite/base.py b/lib/sqlalchemy/dialects/sqlite/base.py index b78423d329..b8bb052a99 100644 --- a/lib/sqlalchemy/dialects/sqlite/base.py +++ b/lib/sqlalchemy/dialects/sqlite/base.py @@ -396,10 +396,18 @@ new connections through the usage of events:: @event.listens_for(Engine, "connect") def set_sqlite_pragma(dbapi_connection, connection_record): + # the sqlite3 driver will not set PRAGMA foreign_keys + # if autocommit=False; set to True temporarily + ac = dbapi_connection.autocommit + dbapi_connection.autocommit = True + cursor = dbapi_connection.cursor() cursor.execute("PRAGMA foreign_keys=ON") cursor.close() + # restore previous autocommit setting + dbapi_connection.autocommit = ac + .. warning:: When SQLite foreign keys are enabled, it is **not possible**