Python 操作 SQLite:逐连接启用外键,验证事务回滚与历史检查
建表时写了 REFERENCES,为什么不存在的父记录仍能被引用?在 SQLite 中,表结构声明和当前连接的外键执行状态需要分别确认。开发机上的一条成功查询,也不能证明连接池里的其他连接已经正确初始化。本文用两个内存表把开关、事务和历史检查拆开验证,全部数据都是临时构造,不读取或修改任何已有数据库。

一、每个连接都要明确设置,并读回结果
可靠的初始化顺序是:打开连接,确认没有活动事务,执行 PRAGMA foreign_keys = ON,再查询 PRAGMA foreign_keys,只有结果为 1 才继续使用。不要把这一步当成数据库文件的永久属性,也不要猜测当前构建的默认值。官方说明该设置需要逐连接处理,编译选项也可能影响支持情况;读回没有结果时不能当成启用成功。来源:SQLite 外键启用说明。
本文的连接工厂只创建 :memory: 数据库,没有接受磁盘路径的入口。这样重复运行不会碰到真实文件。父表使用整数主键,子表的 parent_id 同时声明 REFERENCES 和 NOT NULL:前者负责引用存在性,后者拒绝空值,两种约束不要混为一谈。子表索引用于关联查找,也不能代替外键声明。
二、避开“命令执行了,开关却没变”
已经执行 BEGIN 或存在待结束的 SAVEPOINT 时,修改 foreign_keys 不会生效,而且不一定抛出异常。若程序先写入再补开关,表面上每行调用都成功,实际可能仍然关闭。下面的初始化函数先检查 in_transaction,遇到活动事务直接报错,不擅自提交或回滚调用方的工作。这个拒绝比悄悄改变事务边界更容易排查。来源:foreign_keys 的事务限制。
示例选择显式 SQL 事务,Python 3.12 及以上使用 autocommit=True,较早版本使用 isolation_level=None,随后通过 BEGIN、COMMIT、ROLLBACK 控制边界。特别注意:前一种模式下,Python 的连接 commit()、rollback() 方法不起作用,所以这里明确执行 SQL。不要直接把这些设置复制进已经采用其他事务管理方式的项目。来源:Python sqlite3 事务控制。
三、把一组业务写入作为整体回滚
将第一段保存为 implementation.py。add_pair 故意允许传入另一个父编号,便于构造失败案例:先插入父记录,再尝试插入指向不存在编号的子记录。事务包装器既处理执行语句时的异常,也处理 COMMIT 发生的异常;后者对延迟约束尤其重要。检测到事务仍活动时执行回滚,随后把原异常继续抛给调用方。
import sqlite3
import sys
from contextlib import contextmanager
def raw_memory():
if sys.version_info >= (3, 12):
return sqlite3.connect(":memory:", autocommit=True)
return sqlite3.connect(":memory:", isolation_level=None)
def enable_foreign_keys(conn):
if conn.in_transaction:
raise RuntimeError("Enable foreign keys before BEGIN")
conn.execute("PRAGMA foreign_keys = ON")
if conn.execute("PRAGMA foreign_keys").fetchone() != (1,):
raise RuntimeError("Foreign key enforcement unavailable")
def new_database():
conn = raw_memory()
try:
enable_foreign_keys(conn)
conn.execute("CREATE TABLE parent(id INTEGER PRIMARY KEY)")
conn.execute(
"CREATE TABLE child("
"id INTEGER PRIMARY KEY, "
"parent_id INTEGER NOT NULL REFERENCES parent(id))"
)
conn.execute("CREATE INDEX child_parent ON child(parent_id)")
return conn
except BaseException:
conn.close()
raise
@contextmanager
def transaction(conn):
if conn.in_transaction:
raise RuntimeError("Nested transactions are not supported")
conn.execute("BEGIN")
try:
yield
conn.execute("COMMIT")
except BaseException:
if conn.in_transaction:
conn.execute("ROLLBACK")
raise
def add_pair(conn, parent_id, child_id, referenced_id):
with transaction(conn):
conn.execute("INSERT INTO parent VALUES (?)", (parent_id,))
conn.execute(
"INSERT INTO child VALUES (?, ?)", (child_id, referenced_id)
)
def violations(conn):
return conn.execute("PRAGMA main.foreign_key_check").fetchall()
if __name__ == "__main__":
print("Python", sys.version.split()[0], "SQLite", sqlite3.sqlite_version)
db = new_database()
try:
add_pair(db, 1, 10, 1)
try:
add_pair(db, 2, 20, 999)
except sqlite3.IntegrityError:
print("Invalid batch rolled back")
print("Parents:", db.execute("SELECT * FROM parent").fetchall())
print("Violations:", violations(db))
finally:
db.close()运行 python implementation.py,示例会先提交合法关系,然后报告非法批次已回滚,最终父表只保留编号 1,检查结果为空。关键断言不是“捕获到了异常”,而是失败批次之前插入的父记录也没有留下。若只忽略异常并继续提交,业务操作仍可能只完成一半。这个包装器不支持嵌套事务;需要嵌套语义时,应另外设计保存点协议,不能重复执行 BEGIN。
四、检查历史问题,不等于自动修复
开启外键执行不会重新扫描并修好以前写入的所有数据。测试会先在关闭状态下制造一条孤儿行,再打开开关:旧行依然存在,新插入的非法引用则被拒绝。这正是为何上线前既要检查连接初始化,也要检查历史数据,两个动作的目标不同。
PRAGMA main.foreign_key_check 返回每项违规的子表名、子行 rowid、父表名和外键编号。没有 rowid 的子表可能返回空值;编号对应 foreign_key_list 的标识,不能当成业务记录编号。它报告问题,不会帮你选修复方案,也不会顺带打开外键执行。下面测试明确验证,检查结束后关闭状态仍保持关闭。来源:foreign_key_check 返回字段。
在虚构案例中补上编号 999 的父记录,可以让违规消失;真实业务里,这样做可能制造一条没有依据的主体记录。应先确认关系应当指向谁,再决定修正引用、补齐合法实体,或按经过审核的规则处理孤儿数据。检查为空只说明当前范围、当前时点未发现这些外键违规,不证明权限、备份、字段内容或所有业务规则都正确,也不能代替后续连接持续执行约束。
检查历史数据之前还要确定范围。本文显式检查主数据库,没有演示附加数据库或在线迁移。真实环境应先在经过授权的副本上验证流程,记录受影响的表和行,再根据维护窗口安排执行。不要因测试中的内存库很小,就推断生产库的全量检查也没有时间与锁竞争成本;也不要把检测结果直接转换成删除命令。
五、用十个测试检查行为,而非只看建表语句
第二段保存为同目录的 test_implementation.py,执行 python test_implementation.py。每个测试都重新创建内存库,关闭开关的操作只用于复现实验,不能作为线上绕过校验的建议。测试覆盖逐连接状态、成功提交、整批回滚、父表删除保护、非空约束、事务内设置无效、初始化拒绝活动事务、历史违规检查、延迟提交失败及嵌套拒绝。
import sqlite3
import sys
import unittest
from implementation import (
add_pair, enable_foreign_keys, new_database,
raw_memory, transaction, violations,
)
class ForeignKeyTests(unittest.TestCase):
def setUp(self):
self.db = new_database()
self.addCleanup(self.db.close)
def count(self, table):
queries = {
"parent": "SELECT COUNT(*) FROM parent",
"child": "SELECT COUNT(*) FROM child",
}
return self.db.execute(queries[table]).fetchone()[0]
def test_01_each_connection_has_own_switch(self):
other = raw_memory()
self.addCleanup(other.close)
other.execute("PRAGMA foreign_keys = OFF")
self.assertEqual(other.execute("PRAGMA foreign_keys").fetchone(), (0,))
self.assertEqual(self.db.execute("PRAGMA foreign_keys").fetchone(), (1,))
enable_foreign_keys(other)
self.assertEqual(other.execute("PRAGMA foreign_keys").fetchone(), (1,))
def test_02_valid_pair_commits(self):
add_pair(self.db, 1, 10, 1)
self.assertEqual((self.count("parent"), self.count("child")), (1, 1))
self.assertFalse(self.db.in_transaction)
self.assertEqual(violations(self.db), [])
def test_03_invalid_batch_rolls_back_parent_too(self):
with self.assertRaises(sqlite3.IntegrityError):
add_pair(self.db, 1, 10, 999)
self.assertEqual((self.count("parent"), self.count("child")), (0, 0))
self.assertFalse(self.db.in_transaction)
def test_04_referenced_parent_cannot_be_deleted(self):
add_pair(self.db, 1, 10, 1)
with self.assertRaises(sqlite3.IntegrityError):
with transaction(self.db):
self.db.execute("DELETE FROM parent WHERE id = 1")
self.assertEqual(self.count("parent"), 1)
def test_05_null_is_rejected_by_not_null(self):
with self.assertRaises(sqlite3.IntegrityError):
with transaction(self.db):
self.db.execute("INSERT INTO child VALUES (10, NULL)")
self.assertEqual(self.count("child"), 0)
def test_06_enabling_inside_begin_is_no_op(self):
self.db.execute("PRAGMA foreign_keys = OFF")
self.db.execute("BEGIN")
self.db.execute("PRAGMA foreign_keys = ON")
self.assertEqual(self.db.execute("PRAGMA foreign_keys").fetchone(), (0,))
self.db.execute("INSERT INTO child VALUES (10, 999)")
self.assertEqual(self.count("child"), 1)
self.db.execute("ROLLBACK")
enable_foreign_keys(self.db)
self.assertEqual(self.count("child"), 0)
def test_07_helper_refuses_active_transaction(self):
self.db.execute("BEGIN")
self.db.execute("INSERT INTO parent VALUES (1)")
with self.assertRaises(RuntimeError):
enable_foreign_keys(self.db)
self.assertTrue(self.db.in_transaction)
self.assertEqual(self.count("parent"), 1)
self.db.execute("ROLLBACK")
def test_08_check_reports_but_does_not_repair_old_orphan(self):
self.db.execute("PRAGMA foreign_keys = OFF")
self.db.execute("INSERT INTO child VALUES (10, 999)")
self.assertEqual(violations(self.db), [("child", 10, "parent", 0)])
self.assertEqual(self.db.execute("PRAGMA foreign_keys").fetchone(), (0,))
enable_foreign_keys(self.db)
self.assertEqual(violations(self.db), [("child", 10, "parent", 0)])
self.assertEqual(self.count("child"), 1)
with self.assertRaises(sqlite3.IntegrityError):
self.db.execute("INSERT INTO child VALUES (11, 998)")
self.db.execute("INSERT INTO parent VALUES (999)")
self.assertEqual(violations(self.db), [])
def test_09_deferred_commit_failure_rolls_back(self):
self.db.execute(
"CREATE TABLE delayed("
"id INTEGER PRIMARY KEY, "
"parent_id INTEGER REFERENCES parent(id) "
"DEFERRABLE INITIALLY DEFERRED)"
)
with self.assertRaises(sqlite3.IntegrityError):
with transaction(self.db):
self.db.execute("INSERT INTO parent VALUES (1)")
self.db.execute("INSERT INTO delayed VALUES (20, 999)")
self.assertTrue(self.db.in_transaction)
self.assertEqual(self.count("parent"), 0)
self.assertEqual(self.db.execute("SELECT * FROM delayed").fetchall(), [])
self.assertFalse(self.db.in_transaction)
def test_10_nested_scope_is_rejected(self):
with transaction(self.db):
self.db.execute("INSERT INTO parent VALUES (1)")
with self.assertRaises(RuntimeError):
with transaction(self.db):
pass
self.assertEqual(self.count("parent"), 1)
if __name__ == "__main__":
print("Python", sys.version.split()[0], "SQLite", sqlite3.sqlite_version,
flush=True)
unittest.main(verbosity=2)本次实际运行环境为 Python 3.12.14、SQLite 3.53.1,十项测试全部通过,版本信息由程序输出。较早版本分支保留了相同的显式 SQL 思路,但本次未另行测试其他解释器,不把兼容性设计写成已经完成的多版本认证。实践中应在自己的解释器与 SQLite 构建上重跑,再把初始化函数接入每个新建连接的入口。
排查时可以按固定顺序留证:连接何时创建,开关读回多少,当时是否处于事务中,失败写入是否整体回滚,历史检查是否返回违规。连接池补建连接、任务进程重启或测试夹具重新连接时,都需要重新走初始化入口,不能只在应用启动时对某一个连接设置一次。若无法证明所有写入入口采用相同规则,就保留这个限制,不把局部测试结果扩大成全局保证。先把这些事实记录清楚,再讨论数据修复,比根据一条“启用成功”的日志推断整个应用已经安全更可靠。

