如何在 sqlalchemy 迁移脚本或 sqlite 的配置文件中打开“PRAGMA foreign_keys = ON"? [英] How to turn on 'PRAGMA foreign_keys = ON' in sqlalchemy migration script or configuration file for sqlite?
本文介绍了如何在 sqlalchemy 迁移脚本或 sqlite 的配置文件中打开“PRAGMA foreign_keys = ON"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在合适的 sqlite 版本中,我们可以通过 'PRAGMA foreign_keys = ON' 来强制执行外键约束.但是,用户无法每次建立连接时都登录数据库.所以我想知道我们如何让它在 sqlalchemy/alembic 的迁移脚本中工作?非常感谢!
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!
推荐答案
参见 外键支持来自 SA SQLite 文档:
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()
这篇关于如何在 sqlalchemy 迁移脚本或 sqlite 的配置文件中打开“PRAGMA foreign_keys = ON"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文