From 68fddbaa680b12d89d72cab26c211d1d9c861eae Mon Sep 17 00:00:00 2001 From: Sylvain Leclerc Date: Mon, 7 Oct 2024 14:00:35 +0200 Subject: [PATCH] fix: enable foreign keys for sqlite Signed-off-by: Sylvain Leclerc --- .../utils/fastapi_sqlalchemy/middleware.py | 20 ++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/antarest/core/utils/fastapi_sqlalchemy/middleware.py b/antarest/core/utils/fastapi_sqlalchemy/middleware.py index dcc1f95b25..437a4d3af6 100644 --- a/antarest/core/utils/fastapi_sqlalchemy/middleware.py +++ b/antarest/core/utils/fastapi_sqlalchemy/middleware.py @@ -1,7 +1,7 @@ from contextvars import ContextVar, Token from typing import Any, Dict, Optional, Type, Union -from sqlalchemy import create_engine # type: ignore +from sqlalchemy import create_engine, event # type: ignore from sqlalchemy.engine import Engine # type: ignore from sqlalchemy.engine.url import URL # type: ignore from sqlalchemy.orm import Session, sessionmaker # type: ignore @@ -16,6 +16,24 @@ _session: ContextVar[Optional[Session]] = ContextVar("_session", default=None) +def _is_sqlite_connection(dbapi_connection: Any) -> bool: + cls = dbapi_connection.__class__ + full_classe_name = f"{cls.__module__}{cls.__name__}" + return "sqlite" in full_classe_name + + +@event.listens_for(Engine, "connect") # type: ignore +def enable_sqlite_foreign_keys(dbapi_connection: Any, connection_record: Any) -> None: + """ + By default, sqlite does not enforce foreign key constraints, + we need to tell it explicitly. + """ + if _is_sqlite_connection(dbapi_connection): + cursor = dbapi_connection.cursor() + cursor.execute("PRAGMA foreign_keys=ON;") + cursor.close() + + class DBSessionMiddleware(BaseHTTPMiddleware): def __init__( self,