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

女生的网名这么多〃 提交于 2019-12-01 08:37:21

问题


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!


回答1:


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()



回答2:


SQLite has no logins.

To enable foreign keys in a script, just add the PRAGMA foreign_keys = ON command to that script.



来源:https://stackoverflow.com/questions/13712381/how-to-turn-on-pragma-foreign-keys-on-in-sqlalchemy-migration-script-or-conf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!