From e96bf8608ed2862f538ac0873303c91ed3a7260c Mon Sep 17 00:00:00 2001 From: Mike Bayer Date: Thu, 7 Aug 2025 10:48:51 -0400 Subject: [PATCH] ensure autocommit is not False for SQLite FK pragma References: #12767 References: https://github.com/python/cpython/issues/137205 Change-Id: I6772a4c9c216c6981421043f850cbf833ded2be3 --- lib/sqlalchemy/dialects/sqlite/base.py | 8 ++++++++ 1 file changed, 8 insertions(+) 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** -- 2.47.2