Skip to main content
 首页 » 编程设计

python之SQLAlchemy IntegrityError 违反约束名称

2025年05月04日12java哥

我对数据库表的列有很多不同的约束。插入数据库的数据通常包含数字数组(对这些数字设置了约束),例如(DDL 的一部分):

CREATE TABLE "Object" ( 
    id INTEGER NOT NULL,  
    PRIMARY KEY (id),  
    FOREIGN KEY(id) REFERENCES "Generic" (id)  // Inheritance 
); 
 
CREATE TABLE "ObjectData" ( 
    id INTEGER NOT NULL,  
    x FLOAT NOT NULL,  
    y FLOAT NOT NULL,  
    d FLOAT NOT NULL,  
    a FLOAT NOT NULL,  
    e FLOAT NOT NULL,  
    object_id INTEGER NOT NULL,  
    PRIMARY KEY (id),  
    CONSTRAINT "duplicate x, y values" UNIQUE (x, y, object_id),  
    CONSTRAINT "x must be >= -1.0" CHECK (x >= 0.0),  
    CONSTRAINT "x must be <= 1.0" CHECK (x <= 1.0),  
    CONSTRAINT "y must be >= -1.0" CHECK (y >= -1.0),  
    CONSTRAINT "y must be <= 1.0" CHECK (y <= 1.0),  
    CONSTRAINT "d must be >= -1.0" CHECK (d >= 0.0),  
    CONSTRAINT "d must be <= 1.0" CHECK (d <= 1.0),  
    CONSTRAINT "a must be >= -270.0" CHECK (a >= -270.0),  
    CONSTRAINT "a must be <= 270.0" CHECK (a <= 270.0),  
    CONSTRAINT "e must be >= -1.0" CHECK (e >= -1.0),  
    CONSTRAINT "e must be <= 1.0" CHECK (e <= 1.0),  
    FOREIGN KEY(object_id) REFERENCES "Object" (id) 
); 

插入数据如下所示(解析为插入数据库的输入文本文件的一部分):

DATA: 
-1.0  -1.0  1.0  242.0  0.0 
-1.0  -2.0  1.0  124.0  0.0 
-1.0  -1.0  1.0  109.0  0.0 
........................... 
-1.0  -1.0  1.0  242.0  0.0 
-1.0  -2.0  1.0  124.0  0.0 
-1.0  -1.0  1.0  109.0  0.0 

因此,如果这些值中的任何一个违反约束之一并且不会显示任何消息,那么就很难确定哪些值是错误的。为此,给出了约束的描述性名称。使用 SQLite3 数据库通过 SQLAlchemy ORM 执行,当 sqlalchemy.exc.IntegretyError 发生时,该库会完全切断违反约束的名称。

SQLite3 中 IntegrityError 异常中存在约束名称的谷歌搜索结果已从 [version 3.3.2][1] 开始。这显示了 Python REPL 中的简短测试:

>>> import sqlite3 
>>> conn = sqlite3.connect('test/test.db') 
>>> c = conn.cursor() 
>>> c.execute("""INSERT INTO "ObjectData" (x, y, d, a, e, object_id) VALUES (?, ?, ?, ?, ?, ?)""", (-2.0, -1.0, 1.0, 242.0, 0.0, 1)) 
Traceback (most recent call last): 
  File "<input>", line 1, in <module> 
IntegrityError: CHECK constraint failed: x must be >= -1.0 

但是当我尝试使用 SQLAlchemy 插入数据时,我只收到无法描述发生了什么错误的消息。这里是 dir(error) 的结果:

detail = [] 
params = (-2.0, -1.0, 1.0, 242.0, 0.0, 1) 
statement = INSERT INTO "ObjectData" (x, y, d, a, e, object_id) VALUES (?, ?, ?, ?, ?, ?) 
instance = <bound method type.instance of <class 'sqlalchemy.exc.IntegrityError'>> 
args = ('(IntegrityError) constraint failed',) 
orig = constraint failed 
orig.message = constraint failed 

所以问题是有什么方法可以强制 SQLAlchemy 返回违反的约束名称,因为它大大简化了代码并允许向用户显示有关错误的信息性消息?或者可能存在其他方式?

请您参考如下方法:

我发现 SQLAlchemy 库的使用有什么问题。当我在 Debug模式下运行软件并在引发 IntegrityError 异常时中断(断点在 SQLAlchemy 库的 DBAPIError.instance 方法中设置)然后我意识到原始错误类型是类 'pysqlite2._sqlite.Error' 而不是 sqlite3。似乎在我的 Python 环境中安装了站点包库 pysqlite2,但这与 sqlite3 不同。我尝试使用简单的解决方法:从站点包中删除 pysqlite2 目录。在原始异常类型变为类“sqlite3.Error”之后,异常中的 orig.message 完全包含我所期望的。所以很明显 SQLAlchemy 默认使用 pysqlite2 库而不是内置的 sqlite3 库。