Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn on 'PRAGMA foreign_keys = ON' in sqlalchemy migration script or configuration file for sqlite?

In a suitable sqlite version, we can enforce foreign key constraint by 'PRAGMA foreign_keys = ON'. However user can not log in a database every time when making a connection. So I wonder how can we make it working in a migration script in sqlalchemy/alembic? Thanks very much!

like image 299
user1342336 Avatar asked Oct 27 '25 10:10

user1342336


1 Answers

See Foreign Key Support from SA SQLite documentation:

import sqlite3

from sqlalchemy.engine import Engine
from sqlalchemy import event

@event.listens_for(Engine, "connect")
def set_sqlite_pragma(dbapi_connection, connection_record):
    if type(dbapi_connection) is sqlite3.Connection:  # play well with other DB backends
       cursor = dbapi_connection.cursor()
       cursor.execute("PRAGMA foreign_keys=ON")
       cursor.close()
like image 160
van Avatar answered Oct 29 '25 23:10

van