Sqlite/SQLAlchemy:如何强制使用外键? [英] Sqlite / SQLAlchemy: how to enforce Foreign Keys?

查看:39
本文介绍了Sqlite/SQLAlchemy:如何强制使用外键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新版本的 SQLite 有强制外键约束的能力,但为了向后兼容,你必须为每个数据库连接单独打开它!

sqlite>PRAGMA foreign_keys = ON;

我正在使用 SQLAlchemy——我如何确保它总是被打开?我试过的是这样的:

engine = sqlalchemy.create_engine('sqlite:///:memory:', echo=True)engine.execute('pragma foreign_keys=on')

...但它不起作用!...我错过了什么?

我认为我真正的问题是我安装了不止一个版本的 SQLite,而 Python 没有使用最新版本!

<预><代码>>>>导入 sqlite3>>>打印 sqlite3.sqlite_version3.3.4

但是我刚下载了3.6.23,把exe放到我的项目目录下!如何确定它使用的是哪个 .exe 并对其进行更改?

解决方案

我现在有这个工作:

如上所述下载最新的 sqlite 和 pysqlite2 版本:确保 python 在运行时使用正确的版本.

导入 sqlite3导入 pysqlite2打印 sqlite3.sqlite_version # 应该是 3.6.23.1打印 pysqlite2.__path__ # 例如 C:\Python26\lib\site-packages\pysqlite2

接下来添加一个PoolListener:

from sqlalchemy.interfaces import PoolListener类外键监听器(池监听器):定义连接(自我,dbapi_con,con_record):db_cursor = dbapi_con.execute('pragma foreign_keys=ON')引擎 = create_engine(database_url, listeners=[ForeignKeysListener()])

然后小心你如何测试外键是否有效:我在这里有些困惑.当使用 sqlalchemy ORM 到 add() 事情时,我的导入代码隐式处理关系连接,因此永远不会失败.将 nullable=False 添加到一些 ForeignKey() 语句对我有帮助.

我测试启用 sqlalchemy sqlite 外键支持的方法是从声明性 ORM 类中手动插入:

# 示例ins = Coverage.__table__.insert().values(id = 99,描述 = '错误',面积 = 42.0,wall_id = 99, # 无效的 fkey idtype_id = 99) # 无效的 fkey_idsession.execute(ins)

这里的 wall_idtype_id 都是 ForeignKey() 的,如果尝试连接无效的 fkeys,sqlite 现在会正确抛出异常.所以它有效!如果您删除侦听器,那么 sqlalchemy 将很乐意添加无效条目.

我认为主要问题可能是多个 sqlite3.dll(或 .so)存在.

The new version of SQLite has the ability to enforce Foreign Key constraints, but for the sake of backwards-compatibility, you have to turn it on for each database connection separately!

sqlite> PRAGMA foreign_keys = ON;

I am using SQLAlchemy -- how can I make sure this always gets turned on? What I have tried is this:

engine = sqlalchemy.create_engine('sqlite:///:memory:', echo=True)
engine.execute('pragma foreign_keys=on')

...but it is not working!...What am I missing?

EDIT: I think my real problem is that I have more than one version of SQLite installed, and Python is not using the latest one!

>>> import sqlite3
>>> print sqlite3.sqlite_version
3.3.4

But I just downloaded 3.6.23 and put the exe in my project directory! How can I figure out which .exe it's using, and change it?

解决方案

I now have this working:

Download the latest sqlite and pysqlite2 builds as described above: make sure correct versions are being used at runtime by python.

import sqlite3   
import pysqlite2 
print sqlite3.sqlite_version   # should be 3.6.23.1
print pysqlite2.__path__       # eg C:\Python26\lib\site-packages\pysqlite2

Next add a PoolListener:

from sqlalchemy.interfaces import PoolListener
class ForeignKeysListener(PoolListener):
    def connect(self, dbapi_con, con_record):
        db_cursor = dbapi_con.execute('pragma foreign_keys=ON')

engine = create_engine(database_url, listeners=[ForeignKeysListener()])

Then be careful how you test if foreign keys are working: I had some confusion here. When using sqlalchemy ORM to add() things my import code was implicitly handling the relation hookups so could never fail. Adding nullable=False to some ForeignKey() statements helped me here.

The way I test sqlalchemy sqlite foreign key support is enabled is to do a manual insert from a declarative ORM class:

# example
ins = Coverage.__table__.insert().values(id = 99,
                                    description = 'Wrong',
                                    area = 42.0,
                                    wall_id = 99,  # invalid fkey id
                                    type_id = 99)  # invalid fkey_id
session.execute(ins) 

Here wall_id and type_id are both ForeignKey()'s and sqlite throws an exception correctly now if trying to hookup invalid fkeys. So it works! If you remove the listener then sqlalchemy will happily add invalid entries.

I believe the main problem may be multiple sqlite3.dll's (or .so) lying around.

这篇关于Sqlite/SQLAlchemy:如何强制使用外键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆