]> git.ipfire.org Git - thirdparty/sqlalchemy/sqlalchemy.git/commitdiff
ensure autocommit is not False for SQLite FK pragma main
authorMike Bayer <mike_mp@zzzcomputing.com>
Thu, 7 Aug 2025 14:48:51 +0000 (10:48 -0400)
committerMike Bayer <mike_mp@zzzcomputing.com>
Thu, 7 Aug 2025 14:51:47 +0000 (10:51 -0400)
References: #12767
References: https://github.com/python/cpython/issues/137205
Change-Id: I6772a4c9c216c6981421043f850cbf833ded2be3

lib/sqlalchemy/dialects/sqlite/base.py

index b78423d3297f299607c871b0adbcaf004ccbbd01..b8bb052a99ffc1b99e689fdf8824fb45c3765528 100644 (file)
@@ -396,10 +396,18 @@ new connections through the usage of events::
 
     @event.listens_for(Engine, "connect")
     def set_sqlite_pragma(dbapi_connection, connection_record):
 
     @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()
 
         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**
 .. warning::
 
     When SQLite foreign keys are enabled, it is **not possible**