[db] Always run PRAGMA foreign_keys = ON on SQLite connections.

This is the default behaviour on basically any other supported RDBMS.
This commit is contained in:
Fabio Manganiello 2024-09-01 01:04:12 +02:00
parent a3eedc6adc
commit 7cc7009d08
Signed by: blacklight
GPG key ID: D90FBA7F76362774
2 changed files with 8 additions and 7 deletions

View file

@ -533,13 +533,19 @@ class DbPlugin(Plugin):
with lock, engine.connect() as conn: with lock, engine.connect() as conn:
session_maker = scoped_session( session_maker = scoped_session(
sessionmaker( sessionmaker(
expire_on_commit=False, expire_on_commit=kwargs.get('expire_on_commit', False),
autoflush=autoflush, autoflush=autoflush,
) )
) )
session_maker.configure(bind=conn) session_maker.configure(bind=conn)
session = session_maker() 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 yield session
session.flush() session.flush()

View file

@ -4,7 +4,7 @@ from time import time
from traceback import format_exception from traceback import format_exception
from typing import Optional, Any, Collection, Mapping from typing import Optional, Any, Collection, Mapping
from sqlalchemy import or_, text from sqlalchemy import or_
from sqlalchemy.orm import make_transient, Session from sqlalchemy.orm import make_transient, Session
from platypush.config import Config from platypush.config import Config
@ -206,11 +206,6 @@ class EntitiesPlugin(Plugin):
:return: The payload of the deleted entities. :return: The payload of the deleted entities.
""" """
with self._get_session(locked=True) as session: 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] = ( entities: Collection[Entity] = (
session.query(Entity).filter(Entity.id.in_(entities)).all() session.query(Entity).filter(Entity.id.in_(entities)).all()
) )