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

前端 未结 2 592
被撕碎了的回忆
被撕碎了的回忆 2021-01-14 23:49

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 connecti

2条回答
  •  悲哀的现实
    2021-01-15 00:30

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

提交回复
热议问题