From 7cc7009d08fa4f83f00bd1e879ccd1dab9406610 Mon Sep 17 00:00:00 2001 From: Fabio Manganiello Date: Sun, 1 Sep 2024 01:04:12 +0200 Subject: [PATCH] [db] Always run `PRAGMA foreign_keys = ON` on SQLite connections. This is the default behaviour on basically any other supported RDBMS. --- platypush/plugins/db/__init__.py | 8 +++++++- platypush/plugins/entities/__init__.py | 7 +------ 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/platypush/plugins/db/__init__.py b/platypush/plugins/db/__init__.py index e8ac877665..0e4b84a9a1 100644 --- a/platypush/plugins/db/__init__.py +++ b/platypush/plugins/db/__init__.py @@ -533,13 +533,19 @@ class DbPlugin(Plugin): with lock, engine.connect() as conn: session_maker = scoped_session( sessionmaker( - expire_on_commit=False, + expire_on_commit=kwargs.get('expire_on_commit', False), autoflush=autoflush, ) ) session_maker.configure(bind=conn) session = session_maker() + + if str(session.connection().engine.url).startswith('sqlite://'): + # SQLite requires foreign_keys to be explicitly enabled + # in order to proper manage cascade deletions + session.execute(text('PRAGMA foreign_keys = ON')) + yield session session.flush() diff --git a/platypush/plugins/entities/__init__.py b/platypush/plugins/entities/__init__.py index a21181d710..b3ef372f3f 100644 --- a/platypush/plugins/entities/__init__.py +++ b/platypush/plugins/entities/__init__.py @@ -4,7 +4,7 @@ from time import time from traceback import format_exception from typing import Optional, Any, Collection, Mapping -from sqlalchemy import or_, text +from sqlalchemy import or_ from sqlalchemy.orm import make_transient, Session from platypush.config import Config @@ -206,11 +206,6 @@ class EntitiesPlugin(Plugin): :return: The payload of the deleted entities. """ with self._get_session(locked=True) as session: - if str(session.connection().engine.url).startswith('sqlite://'): - # SQLite requires foreign_keys to be explicitly enabled - # in order to proper manage cascade deletions - session.execute(text('PRAGMA foreign_keys = ON')) - entities: Collection[Entity] = ( session.query(Entity).filter(Entity.id.in_(entities)).all() )