Skip to content
This repository was archived by the owner on Jun 5, 2025. It is now read-only.

Commit 2a0f8f1

Browse files
Add pragma to enable foreign key support in SQLite
Co-Authored-By: Alejandro Ponce de Leon <aponcedeleonch@stacklok.com> Signed-off-by: Juan Antonio Osorio <ozz@stacklok.com>
1 parent f3366ba commit 2a0f8f1

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

src/codegate/db/connection.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88
from alembic import command as alembic_command
99
from alembic.config import Config as AlembicConfig
1010
from pydantic import BaseModel
11-
from sqlalchemy import CursorResult, TextClause, text
11+
from sqlalchemy import CursorResult, TextClause, event, text
12+
from sqlalchemy.engine import Engine
1213
from sqlalchemy.exc import IntegrityError, OperationalError
1314
from sqlalchemy.ext.asyncio import create_async_engine
1415

@@ -35,6 +36,20 @@ class AlreadyExistsError(Exception):
3536
pass
3637

3738

39+
@event.listens_for(Engine, "connect")
40+
def set_sqlite_pragma(dbapi_connection, connection_record):
41+
"""
42+
Ensures that foreign keys are enabled for the SQLite database at every connection.
43+
SQLite does not enforce foreign keys by default, so we need to enable them manually.
44+
[SQLAlchemy docs](https://docs.sqlalchemy.org/en/20/dialects/sqlite.html#foreign-key-support)
45+
[SQLite docs](https://www.sqlite.org/foreignkeys.html)
46+
[SO](https://stackoverflow.com/questions/2614984/sqlite-sqlalchemy-how-to-enforce-foreign-keys)
47+
"""
48+
cursor = dbapi_connection.cursor()
49+
cursor.execute("PRAGMA foreign_keys=ON")
50+
cursor.close()
51+
52+
3853
class DbCodeGate:
3954
_instance = None
4055

0 commit comments

Comments
 (0)