Sqlite/SQLAlchemy:如何强制使用外键?

2023-09-18数据库问题
1

本文介绍了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:如何强制使用外键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

Mysql目录里的ibtmp1文件过大造成磁盘占满的解决办法
ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致...
2025-01-02 数据库问题
151

按天分组的 SQL 查询
SQL query to group by day(按天分组的 SQL 查询)...
2024-04-16 数据库问题
77

SQL 子句“GROUP BY 1"是什么意思?意思是?
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)...
2024-04-16 数据库问题
62

MySQL groupwise MAX() 返回意外结果
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)...
2024-04-16 数据库问题
13

MySQL SELECT 按组最频繁
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)...
2024-04-16 数据库问题
16

在 Group By 查询中包含缺失的月份
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)...
2024-04-16 数据库问题
12