Python sqlite3 闭包表实战:层级权限与分类的距离维护
分类树和授权范围经常需要查询全部祖先或后代。如果每次读取都重新沿父链遍历,写入很简单,读取却要不断计算。同样一份层级结构,也可以把所有祖先与后代关系提前存成闭包表。本文不展开递归查询语法,而是集中解决物化路径的维护成本:什么必须始终成立,移动后距离如何变化,以及怎样发现和修复漂移。

九段代码均可单独保存为 Python 文件执行,不依赖前面的脚本或外部包;为保证独立性,建表与辅助函数会重复出现。示例面向 Python 3.10 及以上版本,实际在 Python 3.12.14 与 SQLite 3.53.1 上使用开发模式、将警告视为错误执行,并逐段核对标准输出。所有数据保存在各自的内存数据库里,代码中的断言是教学测试,不是生产环境输入校验的替代品。
一、先把距离不变量写进表结构
本文处理单父节点的树或森林:每个节点至多一个父节点,父链最终到达空值。节点表保存直接父子关系,闭包表保存全部祖先与后代组合。对任意节点,必须有一条自身到自身、距离为零的记录;两个不同节点之间只要存在祖先关系,就必须有且仅有一条记录,距离等于连接它们的父子边数。没有祖先关系的组合不能出现。距离不是节点编号差,也不是全局层级。
节点表是本方案的结构事实,闭包表是需要同步维护的物化结果。主键阻止重复组合,外键保证端点存在,检查约束阻止负数、非整数和错误的自身距离。然而这些约束无法保证路径齐全,也无法判断一条距离为三的记录在真实父链中是否其实只有两步。把约束检查通过误认为闭包正确,是这类实现最危险的起点。
import sqlite3
from contextlib import closing, contextmanager
def connect():
options = {"isolation_level": None}
if hasattr(sqlite3, "LEGACY_TRANSACTION_CONTROL"):
options["autocommit"] = sqlite3.LEGACY_TRANSACTION_CONTROL
db = sqlite3.connect(":memory:", **options)
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
db.executescript("""
CREATE TABLE node (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
parent_id INTEGER REFERENCES node(id) ON DELETE RESTRICT,
CHECK (parent_id IS NULL OR parent_id <> id)
);
CREATE INDEX node_parent ON node(parent_id);
CREATE TABLE closure (
ancestor INTEGER NOT NULL REFERENCES node(id) ON DELETE CASCADE,
descendant INTEGER NOT NULL REFERENCES node(id) ON DELETE CASCADE,
distance INTEGER NOT NULL
CHECK (typeof(distance) = 'integer' AND distance >= 0),
PRIMARY KEY (ancestor, descendant),
CHECK ((ancestor = descendant AND distance = 0)
OR (ancestor <> descendant AND distance > 0))
) WITHOUT ROWID;
CREATE INDEX closure_reverse
ON closure(descendant, distance, ancestor);
""")
return db
@contextmanager
def atomic(db):
db.execute("BEGIN IMMEDIATE")
try:
yield
db.execute("COMMIT")
except BaseException:
if db.in_transaction:
db.execute("ROLLBACK")
raise
with closing(connect()) as db:
with atomic(db):
db.execute("INSERT INTO node VALUES (1, 'Root', NULL)")
db.execute("INSERT INTO closure VALUES (1, 1, 0)")
rejected = False
try:
with atomic(db):
db.execute("UPDATE closure SET distance = 1")
except sqlite3.IntegrityError:
rejected = True
assert rejected
assert db.execute("SELECT * FROM closure").fetchall() == [(1, 1, 0)]
print("self distance rejected:", rejected)
print("rows:", db.execute("SELECT * FROM closure").fetchall())预期输出:
self distance rejected: True rows: [(1, 1, 0)]
这里有意使用显式事务:连接设为不隐式开启事务的模式,再由操作函数发出开始、提交或回滚语句。新版本 Python 若提供旧式事务控制常量,也显式指定它,避免未来默认值变化影响示例。初始化脚本只用于建表,放在业务事务之外;事务内逐条执行语句。每个连接都在事务开始之前开启并确认外键,最后明确关闭。相关行为以 Python sqlite3 事务控制文档及 SQLite 外键文档为准。
二、新增叶子时复制父节点的全部祖先
把新节点挂到某个父节点下面,新增的路径只有两类:新节点自己的零距离记录,以及父节点的每一位祖先到新节点的记录。后者的距离统一在原值上加一。父节点自身也在祖先集合内,因此距离为一的直接边会自然生成,不必另外补一条。新增一个根节点时只有自身记录,森林中不同根的分支不会互相连接。
节点写入和闭包写入必须属于同一个事务。若先提交节点再填闭包,另一个请求可能读到一个存在却无法被祖先查询找到的分类。下面的辅助函数只负责执行步骤,事务边界归调用者管理,因而批量插入可以共用一次事务。它要求调用前的闭包已经正确;若库已经发生漂移,应先运行后文的审计,而不是继续从错误缓存派生更多错误。
import sqlite3
from contextlib import closing, contextmanager
def connect():
options = {"isolation_level": None}
if hasattr(sqlite3, "LEGACY_TRANSACTION_CONTROL"):
options["autocommit"] = sqlite3.LEGACY_TRANSACTION_CONTROL
db = sqlite3.connect(":memory:", **options)
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
db.executescript("""
CREATE TABLE node (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
parent_id INTEGER REFERENCES node(id) ON DELETE RESTRICT,
CHECK (parent_id IS NULL OR parent_id <> id)
);
CREATE INDEX node_parent ON node(parent_id);
CREATE TABLE closure (
ancestor INTEGER NOT NULL REFERENCES node(id) ON DELETE CASCADE,
descendant INTEGER NOT NULL REFERENCES node(id) ON DELETE CASCADE,
distance INTEGER NOT NULL
CHECK (typeof(distance) = 'integer' AND distance >= 0),
PRIMARY KEY (ancestor, descendant),
CHECK ((ancestor = descendant AND distance = 0)
OR (ancestor <> descendant AND distance > 0))
) WITHOUT ROWID;
CREATE INDEX closure_reverse
ON closure(descendant, distance, ancestor);
""")
return db
@contextmanager
def atomic(db):
db.execute("BEGIN IMMEDIATE")
try:
yield
db.execute("COMMIT")
except BaseException:
if db.in_transaction:
db.execute("ROLLBACK")
raise
def add_leaf(db, node_id, name, parent_id):
# Call only inside the caller's transaction.
assert db.in_transaction
if parent_id is not None and not db.execute(
"SELECT 1 FROM node WHERE id = ?", (parent_id,)
).fetchone():
raise ValueError("parent not found")
db.execute("INSERT INTO node VALUES (?, ?, ?)",
(node_id, name, parent_id))
db.execute("INSERT INTO closure VALUES (?, ?, 0)", (node_id, node_id))
if parent_id is not None:
db.execute("""
INSERT INTO closure(ancestor, descendant, distance)
SELECT ancestor, ?, distance + 1
FROM closure WHERE descendant = ?
""", (node_id, parent_id))
with closing(connect()) as db:
with atomic(db):
add_leaf(db, 1, "Root", None)
add_leaf(db, 2, "Books", 1)
add_leaf(db, 4, "Python", 2)
paths = db.execute("""
SELECT ancestor, distance FROM closure
WHERE descendant = 4 ORDER BY distance
""").fetchall()
assert paths == [(4, 0), (2, 1), (1, 2)]
print("ancestors:", paths)
assert db.execute("SELECT count(*) FROM closure").fetchone() == (6,)
print("closure rows:", 6)预期输出:
ancestors: [(4, 0), (2, 1), (1, 2)] closure rows: 6
链上三个节点共有六条记录,而不是三条。更一般地,闭包行数等于每个节点的深度加一之后再求和。长链的总行数达到节点数与节点数加一之积的一半;浅而宽的分类树则通常小得多。这是用空间和写放大换取读路径简单化,不能只凭一次查询变快就决定采用。
三、子树查询直接读取距离,不再现场遍历
从第三个示例开始,固定使用六个节点:根节点下有图书和数字内容;图书下面是 Python,Python 下面是异步专题;数字内容下面是视频。查询图书子树时,只需按祖先编号过滤闭包表,再连接节点名。自身记录让是否包含根节点成为一个明确的过滤条件。
距离上限适合只展开两层目录的界面,但距离必须相对于本次查询的根。按距离再按编号排序得到的是逐层展示顺序,不是把每棵子树连续排在一起的深度优先目录。如果前端需要自定义同级顺序,应另存排序字段并另行设计展示排序,不能指望闭包表的物理存储顺序替代产品规则。
import sqlite3
from contextlib import closing, contextmanager
def connect():
options = {"isolation_level": None}
if hasattr(sqlite3, "LEGACY_TRANSACTION_CONTROL"):
options["autocommit"] = sqlite3.LEGACY_TRANSACTION_CONTROL
db = sqlite3.connect(":memory:", **options)
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
db.executescript("""
CREATE TABLE node (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
parent_id INTEGER REFERENCES node(id) ON DELETE RESTRICT,
CHECK (parent_id IS NULL OR parent_id <> id)
);
CREATE INDEX node_parent ON node(parent_id);
CREATE TABLE closure (
ancestor INTEGER NOT NULL REFERENCES node(id) ON DELETE CASCADE,
descendant INTEGER NOT NULL REFERENCES node(id) ON DELETE CASCADE,
distance INTEGER NOT NULL
CHECK (typeof(distance) = 'integer' AND distance >= 0),
PRIMARY KEY (ancestor, descendant),
CHECK ((ancestor = descendant AND distance = 0)
OR (ancestor <> descendant AND distance > 0))
) WITHOUT ROWID;
CREATE INDEX closure_reverse
ON closure(descendant, distance, ancestor);
""")
return db
@contextmanager
def atomic(db):
db.execute("BEGIN IMMEDIATE")
try:
yield
db.execute("COMMIT")
except BaseException:
if db.in_transaction:
db.execute("ROLLBACK")
raise
def add_leaf(db, node_id, name, parent_id):
# Call only inside the caller's transaction.
assert db.in_transaction
if parent_id is not None and not db.execute(
"SELECT 1 FROM node WHERE id = ?", (parent_id,)
).fetchone():
raise ValueError("parent not found")
db.execute("INSERT INTO node VALUES (?, ?, ?)",
(node_id, name, parent_id))
db.execute("INSERT INTO closure VALUES (?, ?, 0)", (node_id, node_id))
if parent_id is not None:
db.execute("""
INSERT INTO closure(ancestor, descendant, distance)
SELECT ancestor, ?, distance + 1
FROM closure WHERE descendant = ?
""", (node_id, parent_id))
def seed(db):
rows = [(1, "Root", None), (2, "Books", 1), (3, "Digital", 1),
(4, "Python", 2), (5, "Async", 4), (6, "Video", 3)]
with atomic(db):
for row in rows:
add_leaf(db, *row)
with closing(connect()) as db:
seed(db)
rows = db.execute("""
SELECT n.id, n.name, c.distance
FROM closure AS c JOIN node AS n ON n.id = c.descendant
WHERE c.ancestor = ? AND c.distance BETWEEN 1 AND 2
ORDER BY c.distance, n.id
""", (2,)).fetchall()
assert rows == [(4, "Python", 1), (5, "Async", 2)]
print("descendants:", rows)
direct = db.execute("""
SELECT descendant FROM closure
WHERE ancestor = ? AND distance = 1 ORDER BY descendant
""", (1,)).fetchall()
assert direct == [(2,), (3,)]
print("root children:", [row[0] for row in direct])预期输出:
descendants: [(4, 'Python', 1), (5, 'Async', 2)] root children: [2, 3]
复合主键以祖先编号开头,适合固定祖先找后代;反向索引以归属节点编号开头,适合固定后代找祖先。是否还需要祖先、距离、后代的额外索引,取决于按距离筛选的频率、树的规模和实际查询计划。索引也会放大移动和重建成本,先测量再增加。SQLite 官方的 查询优化器概览说明了复合索引的使用条件。
四、权限范围可以继承,授权语义仍需明确
闭包适合回答一个较窄的问题:某项资源是否落在某个已授权范围内。下面采用仅允许、向下继承的简化模型,给某位用户授权图书节点后,图书及其全部后代都在可见范围内。给同一个人同时授权父节点和子节点,会产生重复匹配,因此查询使用存在性判断,而不是让连接结果直接膨胀成重复资源行。
这不是完整的权限系统。拒绝规则优先级、租户边界、用户组、有效期、操作类型以及跨范围共享,都必须另外定义。尤其不能把最近祖先的距离最小这一事实,直接解释成业务上优先级最高;那是一项产品决策。闭包表只证明结构可达性,不能替系统决定授权政策。
import sqlite3
from contextlib import closing, contextmanager
def connect():
options = {"isolation_level": None}
if hasattr(sqlite3, "LEGACY_TRANSACTION_CONTROL"):
options["autocommit"] = sqlite3.LEGACY_TRANSACTION_CONTROL
db = sqlite3.connect(":memory:", **options)
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
db.executescript("""
CREATE TABLE node (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
parent_id INTEGER REFERENCES node(id) ON DELETE RESTRICT,
CHECK (parent_id IS NULL OR parent_id <> id)
);
CREATE INDEX node_parent ON node(parent_id);
CREATE TABLE closure (
ancestor INTEGER NOT NULL REFERENCES node(id) ON DELETE CASCADE,
descendant INTEGER NOT NULL REFERENCES node(id) ON DELETE CASCADE,
distance INTEGER NOT NULL
CHECK (typeof(distance) = 'integer' AND distance >= 0),
PRIMARY KEY (ancestor, descendant),
CHECK ((ancestor = descendant AND distance = 0)
OR (ancestor <> descendant AND distance > 0))
) WITHOUT ROWID;
CREATE INDEX closure_reverse
ON closure(descendant, distance, ancestor);
""")
return db
@contextmanager
def atomic(db):
db.execute("BEGIN IMMEDIATE")
try:
yield
db.execute("COMMIT")
except BaseException:
if db.in_transaction:
db.execute("ROLLBACK")
raise
def add_leaf(db, node_id, name, parent_id):
# Call only inside the caller's transaction.
assert db.in_transaction
if parent_id is not None and not db.execute(
"SELECT 1 FROM node WHERE id = ?", (parent_id,)
).fetchone():
raise ValueError("parent not found")
db.execute("INSERT INTO node VALUES (?, ?, ?)",
(node_id, name, parent_id))
db.execute("INSERT INTO closure VALUES (?, ?, 0)", (node_id, node_id))
if parent_id is not None:
db.execute("""
INSERT INTO closure(ancestor, descendant, distance)
SELECT ancestor, ?, distance + 1
FROM closure WHERE descendant = ?
""", (node_id, parent_id))
def seed(db):
rows = [(1, "Root", None), (2, "Books", 1), (3, "Digital", 1),
(4, "Python", 2), (5, "Async", 4), (6, "Video", 3)]
with atomic(db):
for row in rows:
add_leaf(db, *row)
with closing(connect()) as db:
seed(db)
db.execute("""
CREATE TABLE grant_scope (
user_id INTEGER NOT NULL,
node_id INTEGER NOT NULL REFERENCES node(id),
PRIMARY KEY (user_id, node_id)
)
""")
with atomic(db):
db.executemany("INSERT INTO grant_scope VALUES (?, ?)",
[(7, 2), (7, 4)])
visible = db.execute("""
SELECT n.id FROM node AS n
WHERE EXISTS (
SELECT 1 FROM grant_scope AS g
JOIN closure AS c ON c.ancestor = g.node_id
WHERE g.user_id = ? AND c.descendant = n.id
) ORDER BY n.id
""", (7,)).fetchall()
assert visible == [(2,), (4,), (5,)]
print("visible:", [row[0] for row in visible])
assert (6,) not in visible
print("video allowed:", False)预期输出:
visible: [2, 4, 5] video allowed: False
一旦分类关系兼任授权范围,移动子树就同时改变继承权限。移动之前应做授权检查,必要时展示哪些资源会失去或获得可见性;提交之后还要失效相关权限缓存。数据库能保证两张表一起变更,但无法自动替业务补全这些后续动作。
五、跨分支移动只替换穿过子树边界的路径
现在把 Python 整棵子树从图书下面搬到视频下面。子树内部的 Python 到异步专题这条路径没有改变;需要删除的是旧的外部祖先到子树全部节点的组合,再添加新父节点的全部祖先到这些节点的组合。即使某个祖先在移动前后都存在,例如根节点,它到子树的距离也可能改变,因此不能简单跳过共同祖先。
算法先在写事务里冻结三个集合:源节点的后代及相对距离、源节点的严格祖先、新父节点的祖先及相对距离。新增路径的距离是新祖先到新父节点的距离,加上新接入的一条边,再加源节点到目标后代的距离。自身零距离记录在这里尤其重要,它让新父节点和源节点都被统一公式覆盖。
import sqlite3
from contextlib import closing, contextmanager
def connect():
options = {"isolation_level": None}
if hasattr(sqlite3, "LEGACY_TRANSACTION_CONTROL"):
options["autocommit"] = sqlite3.LEGACY_TRANSACTION_CONTROL
db = sqlite3.connect(":memory:", **options)
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
db.executescript("""
CREATE TABLE node (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
parent_id INTEGER REFERENCES node(id) ON DELETE RESTRICT,
CHECK (parent_id IS NULL OR parent_id <> id)
);
CREATE INDEX node_parent ON node(parent_id);
CREATE TABLE closure (
ancestor INTEGER NOT NULL REFERENCES node(id) ON DELETE CASCADE,
descendant INTEGER NOT NULL REFERENCES node(id) ON DELETE CASCADE,
distance INTEGER NOT NULL
CHECK (typeof(distance) = 'integer' AND distance >= 0),
PRIMARY KEY (ancestor, descendant),
CHECK ((ancestor = descendant AND distance = 0)
OR (ancestor <> descendant AND distance > 0))
) WITHOUT ROWID;
CREATE INDEX closure_reverse
ON closure(descendant, distance, ancestor);
""")
return db
@contextmanager
def atomic(db):
db.execute("BEGIN IMMEDIATE")
try:
yield
db.execute("COMMIT")
except BaseException:
if db.in_transaction:
db.execute("ROLLBACK")
raise
def add_leaf(db, node_id, name, parent_id):
# Call only inside the caller's transaction.
assert db.in_transaction
if parent_id is not None and not db.execute(
"SELECT 1 FROM node WHERE id = ?", (parent_id,)
).fetchone():
raise ValueError("parent not found")
db.execute("INSERT INTO node VALUES (?, ?, ?)",
(node_id, name, parent_id))
db.execute("INSERT INTO closure VALUES (?, ?, 0)", (node_id, node_id))
if parent_id is not None:
db.execute("""
INSERT INTO closure(ancestor, descendant, distance)
SELECT ancestor, ?, distance + 1
FROM closure WHERE descendant = ?
""", (node_id, parent_id))
def seed(db):
rows = [(1, "Root", None), (2, "Books", 1), (3, "Digital", 1),
(4, "Python", 2), (5, "Async", 4), (6, "Video", 3)]
with atomic(db):
for row in rows:
add_leaf(db, *row)
def move_subtree(db, source, new_parent, fail_after_delete=False):
with atomic(db):
old_parent = db.execute(
"SELECT parent_id FROM node WHERE id = ?", (source,)
).fetchone()
if old_parent is None or not db.execute(
"SELECT 1 FROM node WHERE id = ?", (new_parent,)
).fetchone():
raise ValueError("node not found")
if db.execute("""
SELECT 1 FROM closure WHERE ancestor = ? AND descendant = ?
""", (source, new_parent)).fetchone():
raise ValueError("target is inside subtree")
if old_parent[0] == new_parent:
return (0, 0)
# Freeze all three sets before deleting any materialized paths.
subtree = db.execute("""
SELECT descendant, distance FROM closure WHERE ancestor = ?
""", (source,)).fetchall()
old = db.execute("""
SELECT ancestor FROM closure
WHERE descendant = ? AND distance > 0
""", (source,)).fetchall()
new = db.execute("""
SELECT ancestor, distance FROM closure WHERE descendant = ?
""", (new_parent,)).fetchall()
removed = [(a, d) for (a,) in old for d, _ in subtree]
db.executemany("""
DELETE FROM closure WHERE ancestor = ? AND descendant = ?
""", removed)
if fail_after_delete:
raise RuntimeError("injected failure")
db.execute("UPDATE node SET parent_id = ? WHERE id = ?",
(new_parent, source))
added = [(a, d, up + 1 + down)
for a, up in new for d, down in subtree]
db.executemany("INSERT INTO closure VALUES (?, ?, ?)", added)
return (len(removed), len(added))
with closing(connect()) as db:
seed(db)
changed = move_subtree(db, 4, 6)
paths = db.execute("""
SELECT ancestor, distance FROM closure
WHERE descendant = 5 ORDER BY distance
""").fetchall()
assert changed == (4, 6)
assert paths == [(5, 0), (4, 1), (6, 2), (3, 3), (1, 4)]
assert db.execute("SELECT parent_id FROM node WHERE id = 4").fetchone() == (6,)
assert not db.execute("""
SELECT 1 FROM closure WHERE ancestor = 2 AND descendant = 5
""").fetchone()
print("removed, added:", changed)
print("new ancestors:", paths)预期输出:
removed, added: (4, 6) new ancestors: [(5, 0), (4, 1), (6, 2), (3, 3), (1, 4)]
开始事务后才检查目标和取集合,避免先读后写之间结构变化。目标在源子树中时会拒绝,自身也属于源子树,因而顺便覆盖了移动到自己的情况。SQLite 同时只能有一个写事务,立即开始写事务可以尽早发现写入竞争,但仍可能失败或等待;它不是无限重试机制。这里的事务包装在提交或步骤出错时回滚,调用方可根据业务幂等性决定是否重试。详见 SQLite 事务文档。
为便于复核,本例把三个集合放入 Python 内存,逐条参数化删除和插入,便于明确展示边界。大子树可改用事务内临时表与集合式语句,核心集合和距离公式不变。不要使用忽略冲突的插入来掩盖残留路径;冲突通常说明维护逻辑或现有闭包不符合假设,应回滚并调查。
六、故障注入验证两张表确实共同回滚
只验证成功移动远远不够。最容易损坏数据的时刻,恰好是旧路径已删除而新路径尚未写入。第六个例子故意在这一位置抛出异常,并比较事务前后的完整节点表和闭包表。比较全量快照比只看节点数量更有力,因为数量不变时距离仍然可能错误。
同一个例子还尝试把图书移动到自己的后代异步专题之下,证明非法目标不会留下半成品。这里只测试当前事务的回滚语义,不能等同于完成断电、磁盘损坏或者全部并发场景的验证。生产环境还应覆盖提交失败、锁竞争、业务回调异常及迁移中断,并采用与部署一致的日志和持久化设置。
import sqlite3
from contextlib import closing, contextmanager
def connect():
options = {"isolation_level": None}
if hasattr(sqlite3, "LEGACY_TRANSACTION_CONTROL"):
options["autocommit"] = sqlite3.LEGACY_TRANSACTION_CONTROL
db = sqlite3.connect(":memory:", **options)
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
db.executescript("""
CREATE TABLE node (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
parent_id INTEGER REFERENCES node(id) ON DELETE RESTRICT,
CHECK (parent_id IS NULL OR parent_id <> id)
);
CREATE INDEX node_parent ON node(parent_id);
CREATE TABLE closure (
ancestor INTEGER NOT NULL REFERENCES node(id) ON DELETE CASCADE,
descendant INTEGER NOT NULL REFERENCES node(id) ON DELETE CASCADE,
distance INTEGER NOT NULL
CHECK (typeof(distance) = 'integer' AND distance >= 0),
PRIMARY KEY (ancestor, descendant),
CHECK ((ancestor = descendant AND distance = 0)
OR (ancestor <> descendant AND distance > 0))
) WITHOUT ROWID;
CREATE INDEX closure_reverse
ON closure(descendant, distance, ancestor);
""")
return db
@contextmanager
def atomic(db):
db.execute("BEGIN IMMEDIATE")
try:
yield
db.execute("COMMIT")
except BaseException:
if db.in_transaction:
db.execute("ROLLBACK")
raise
def add_leaf(db, node_id, name, parent_id):
# Call only inside the caller's transaction.
assert db.in_transaction
if parent_id is not None and not db.execute(
"SELECT 1 FROM node WHERE id = ?", (parent_id,)
).fetchone():
raise ValueError("parent not found")
db.execute("INSERT INTO node VALUES (?, ?, ?)",
(node_id, name, parent_id))
db.execute("INSERT INTO closure VALUES (?, ?, 0)", (node_id, node_id))
if parent_id is not None:
db.execute("""
INSERT INTO closure(ancestor, descendant, distance)
SELECT ancestor, ?, distance + 1
FROM closure WHERE descendant = ?
""", (node_id, parent_id))
def seed(db):
rows = [(1, "Root", None), (2, "Books", 1), (3, "Digital", 1),
(4, "Python", 2), (5, "Async", 4), (6, "Video", 3)]
with atomic(db):
for row in rows:
add_leaf(db, *row)
def move_subtree(db, source, new_parent, fail_after_delete=False):
with atomic(db):
old_parent = db.execute(
"SELECT parent_id FROM node WHERE id = ?", (source,)
).fetchone()
if old_parent is None or not db.execute(
"SELECT 1 FROM node WHERE id = ?", (new_parent,)
).fetchone():
raise ValueError("node not found")
if db.execute("""
SELECT 1 FROM closure WHERE ancestor = ? AND descendant = ?
""", (source, new_parent)).fetchone():
raise ValueError("target is inside subtree")
if old_parent[0] == new_parent:
return (0, 0)
# Freeze all three sets before deleting any materialized paths.
subtree = db.execute("""
SELECT descendant, distance FROM closure WHERE ancestor = ?
""", (source,)).fetchall()
old = db.execute("""
SELECT ancestor FROM closure
WHERE descendant = ? AND distance > 0
""", (source,)).fetchall()
new = db.execute("""
SELECT ancestor, distance FROM closure WHERE descendant = ?
""", (new_parent,)).fetchall()
removed = [(a, d) for (a,) in old for d, _ in subtree]
db.executemany("""
DELETE FROM closure WHERE ancestor = ? AND descendant = ?
""", removed)
if fail_after_delete:
raise RuntimeError("injected failure")
db.execute("UPDATE node SET parent_id = ? WHERE id = ?",
(new_parent, source))
added = [(a, d, up + 1 + down)
for a, up in new for d, down in subtree]
db.executemany("INSERT INTO closure VALUES (?, ?, ?)", added)
return (len(removed), len(added))
with closing(connect()) as db:
seed(db)
def snapshot():
return (db.execute("SELECT * FROM node ORDER BY id").fetchall(),
db.execute("SELECT * FROM closure ORDER BY 1, 2").fetchall())
before = snapshot()
try:
move_subtree(db, 4, 6, fail_after_delete=True)
except RuntimeError as exc:
assert str(exc) == "injected failure"
else:
raise AssertionError("failure was not injected")
assert snapshot() == before and not db.in_transaction
print("rollback preserved both tables:", True)
try:
move_subtree(db, 2, 5)
except ValueError as exc:
assert str(exc) == "target is inside subtree"
else:
raise AssertionError("invalid move accepted")
assert snapshot() == before and not db.in_transaction
print("invalid target rejected:", True)预期输出:
rollback preserved both tables: True invalid target rejected: True
每个公开写入口都应遵守同一事务协议。若其他代码可以直接修改父编号而不更新闭包,再可靠的移动函数也无法保护全局正确性。可以将写操作集中到一个模块,限制直写入口,并把审计加入迁移和维护流程。本文选择应用层统一维护,不能与另一套会重复写闭包的触发器混用。
七、删除叶子与删除整棵子树是两项操作
删除策略必须显式选择。默认删除叶子时,只要节点还有直接子节点就拒绝;删除整棵子树则先固定待删除集合,再按相对距离从大到小删除,让子节点先消失。节点父引用使用限制删除,闭包端点引用使用级联删除:后者只清除关系记录,不会把另一个节点一起删除。这两种级联含义不能混淆。
如果产品要求删除中间分类后把孩子提升给祖父节点,需要对每个孩子执行结构迁移并重新计算外部路径,不能把父引用设为空就算完成。另有商品、授权、附件等业务表引用节点时,还必须分别决定拒绝、迁移、归档或删除,本文仅演示结构表策略。
import sqlite3
from contextlib import closing, contextmanager
def connect():
options = {"isolation_level": None}
if hasattr(sqlite3, "LEGACY_TRANSACTION_CONTROL"):
options["autocommit"] = sqlite3.LEGACY_TRANSACTION_CONTROL
db = sqlite3.connect(":memory:", **options)
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
db.executescript("""
CREATE TABLE node (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
parent_id INTEGER REFERENCES node(id) ON DELETE RESTRICT,
CHECK (parent_id IS NULL OR parent_id <> id)
);
CREATE INDEX node_parent ON node(parent_id);
CREATE TABLE closure (
ancestor INTEGER NOT NULL REFERENCES node(id) ON DELETE CASCADE,
descendant INTEGER NOT NULL REFERENCES node(id) ON DELETE CASCADE,
distance INTEGER NOT NULL
CHECK (typeof(distance) = 'integer' AND distance >= 0),
PRIMARY KEY (ancestor, descendant),
CHECK ((ancestor = descendant AND distance = 0)
OR (ancestor <> descendant AND distance > 0))
) WITHOUT ROWID;
CREATE INDEX closure_reverse
ON closure(descendant, distance, ancestor);
""")
return db
@contextmanager
def atomic(db):
db.execute("BEGIN IMMEDIATE")
try:
yield
db.execute("COMMIT")
except BaseException:
if db.in_transaction:
db.execute("ROLLBACK")
raise
def add_leaf(db, node_id, name, parent_id):
# Call only inside the caller's transaction.
assert db.in_transaction
if parent_id is not None and not db.execute(
"SELECT 1 FROM node WHERE id = ?", (parent_id,)
).fetchone():
raise ValueError("parent not found")
db.execute("INSERT INTO node VALUES (?, ?, ?)",
(node_id, name, parent_id))
db.execute("INSERT INTO closure VALUES (?, ?, 0)", (node_id, node_id))
if parent_id is not None:
db.execute("""
INSERT INTO closure(ancestor, descendant, distance)
SELECT ancestor, ?, distance + 1
FROM closure WHERE descendant = ?
""", (node_id, parent_id))
def seed(db):
rows = [(1, "Root", None), (2, "Books", 1), (3, "Digital", 1),
(4, "Python", 2), (5, "Async", 4), (6, "Video", 3)]
with atomic(db):
for row in rows:
add_leaf(db, *row)
def delete_leaf(db, node_id):
with atomic(db):
if not db.execute("SELECT 1 FROM node WHERE id = ?", (node_id,)).fetchone():
raise ValueError("node not found")
if db.execute("SELECT 1 FROM node WHERE parent_id = ?", (node_id,)).fetchone():
raise ValueError("not a leaf")
db.execute("DELETE FROM node WHERE id = ?", (node_id,))
def delete_subtree(db, root):
with atomic(db):
ids = db.execute("""
SELECT descendant FROM closure WHERE ancestor = ?
ORDER BY distance DESC, descendant
""", (root,)).fetchall()
if not ids:
raise ValueError("node not found")
db.executemany("DELETE FROM node WHERE id = ?", ids)
return [row[0] for row in ids]
with closing(connect()) as db:
seed(db)
try:
delete_leaf(db, 4)
except ValueError as exc:
assert str(exc) == "not a leaf"
else:
raise AssertionError("non-leaf deleted")
removed = delete_subtree(db, 4)
assert removed == [5, 4]
remaining = db.execute("SELECT id FROM node ORDER BY id").fetchall()
assert remaining == [(1,), (2,), (3,), (6,)]
assert db.execute("SELECT count(*) FROM closure").fetchone() == (8,)
assert db.execute("PRAGMA foreign_key_check").fetchall() == []
print("removed:", removed)
print("remaining:", [row[0] for row in remaining])预期输出:
removed: [5, 4] remaining: [1, 2, 3, 6]
从深到浅的次序建立在闭包正确的前提上。发现漂移时应停下相关结构写入,先审计和修复,不要继续依赖错误距离决定删除顺序。SQLite 的 外键动作说明区分了限制删除与级联删除;选择它们时应针对每张业务表分别推演后果。
八、审计必须同时检查缺失、多余与距离错误
数据库约束通过只能说明记录形式合法。下面先故意删掉一条应该存在的祖先关系,再把另一条距离改成九。这两次改动既没有悬空端点,也没有违反非负整数检查,所以外键检查仍然通过。真正的闭包审计需要从节点表独立推导预期集合,然后和现有集合比较。
审计把祖先、后代、距离三个值一起作为集合元素。因此一条距离错误会同时出现在缺失列表与多余列表:缺的是正确距离,多的是错误距离。只比较祖先和后代二元组会漏掉这种问题。推导过程沿父链逐步前进,遇到重复节点或不存在的父节点即停止并报错,避免把损坏的结构误当作可重建的正常输入。
import sqlite3
from contextlib import closing, contextmanager
def connect():
options = {"isolation_level": None}
if hasattr(sqlite3, "LEGACY_TRANSACTION_CONTROL"):
options["autocommit"] = sqlite3.LEGACY_TRANSACTION_CONTROL
db = sqlite3.connect(":memory:", **options)
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
db.executescript("""
CREATE TABLE node (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
parent_id INTEGER REFERENCES node(id) ON DELETE RESTRICT,
CHECK (parent_id IS NULL OR parent_id <> id)
);
CREATE INDEX node_parent ON node(parent_id);
CREATE TABLE closure (
ancestor INTEGER NOT NULL REFERENCES node(id) ON DELETE CASCADE,
descendant INTEGER NOT NULL REFERENCES node(id) ON DELETE CASCADE,
distance INTEGER NOT NULL
CHECK (typeof(distance) = 'integer' AND distance >= 0),
PRIMARY KEY (ancestor, descendant),
CHECK ((ancestor = descendant AND distance = 0)
OR (ancestor <> descendant AND distance > 0))
) WITHOUT ROWID;
CREATE INDEX closure_reverse
ON closure(descendant, distance, ancestor);
""")
return db
@contextmanager
def atomic(db):
db.execute("BEGIN IMMEDIATE")
try:
yield
db.execute("COMMIT")
except BaseException:
if db.in_transaction:
db.execute("ROLLBACK")
raise
def add_leaf(db, node_id, name, parent_id):
# Call only inside the caller's transaction.
assert db.in_transaction
if parent_id is not None and not db.execute(
"SELECT 1 FROM node WHERE id = ?", (parent_id,)
).fetchone():
raise ValueError("parent not found")
db.execute("INSERT INTO node VALUES (?, ?, ?)",
(node_id, name, parent_id))
db.execute("INSERT INTO closure VALUES (?, ?, 0)", (node_id, node_id))
if parent_id is not None:
db.execute("""
INSERT INTO closure(ancestor, descendant, distance)
SELECT ancestor, ?, distance + 1
FROM closure WHERE descendant = ?
""", (node_id, parent_id))
def seed(db):
rows = [(1, "Root", None), (2, "Books", 1), (3, "Digital", 1),
(4, "Python", 2), (5, "Async", 4), (6, "Video", 3)]
with atomic(db):
for row in rows:
add_leaf(db, *row)
def expected_paths(db):
# node.parent_id is the authoritative structure for this application.
parents = dict(db.execute("SELECT id, parent_id FROM node"))
expected = set()
for descendant in parents:
ancestor, distance, seen = descendant, 0, set()
while ancestor is not None:
if ancestor not in parents:
raise ValueError("orphan parent")
if ancestor in seen:
raise ValueError("cycle in node")
seen.add(ancestor)
expected.add((ancestor, descendant, distance))
ancestor = parents[ancestor]
distance += 1
return expected
def audit(db):
expected = expected_paths(db)
actual = set(db.execute("SELECT * FROM closure"))
return sorted(expected - actual), sorted(actual - expected)
with closing(connect()) as db:
seed(db)
with atomic(db):
db.execute("DELETE FROM closure WHERE ancestor = 1 AND descendant = 5")
db.execute("""
UPDATE closure SET distance = 9
WHERE ancestor = 2 AND descendant = 5
""")
with atomic(db):
missing, extra = audit(db)
assert db.execute("PRAGMA foreign_key_check").fetchall() == []
assert missing == [(1, 5, 3), (2, 5, 2)]
assert extra == [(2, 5, 9)]
print("missing:", missing)
print("extra:", extra)预期输出:
missing: [(1, 5, 3), (2, 5, 2)] extra: [(2, 5, 9)]
示例使用写事务取得一致视图,适合简洁的离线维护演示;只读审计也可在适合部署模式的显式读事务中完成。不能用多个相互独立的自动提交查询拼出所谓快照,因为期间发生的合法移动可能被误报成漂移。完整性检查与外键检查各有覆盖范围,业务闭包不变量仍要单独验证,参见 SQLite 外键检查说明。
九、先验证结构,再原子重建物化结果
重建不是把错误闭包当输入再扩展一遍,而是从被明确指定为事实来源的父关系重新生成全部路径。下面先完成结构验证和预期集合计算,再清空旧闭包并写入新集合,最后在同一事务内再次比较。任何一步失败都回滚,因此其他正常连接不应看到一个已提交却只填了一半的结果。
对于大库,预期集合可能占用很多内存,且写事务持续时间会影响其他写入者。应先估算总路径数、备份并安排维护窗口;可以用临时表或受控分批构建降低内存占用,但不能为了分批而把空表和半成品逐批暴露为正式数据。若父关系本身存在环或缺失端点,需要先修复事实来源,重建程序不应猜测用户原来想要的树。
import sqlite3
from contextlib import closing, contextmanager
def connect():
options = {"isolation_level": None}
if hasattr(sqlite3, "LEGACY_TRANSACTION_CONTROL"):
options["autocommit"] = sqlite3.LEGACY_TRANSACTION_CONTROL
db = sqlite3.connect(":memory:", **options)
db.execute("PRAGMA foreign_keys = ON")
assert db.execute("PRAGMA foreign_keys").fetchone() == (1,)
db.executescript("""
CREATE TABLE node (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
parent_id INTEGER REFERENCES node(id) ON DELETE RESTRICT,
CHECK (parent_id IS NULL OR parent_id <> id)
);
CREATE INDEX node_parent ON node(parent_id);
CREATE TABLE closure (
ancestor INTEGER NOT NULL REFERENCES node(id) ON DELETE CASCADE,
descendant INTEGER NOT NULL REFERENCES node(id) ON DELETE CASCADE,
distance INTEGER NOT NULL
CHECK (typeof(distance) = 'integer' AND distance >= 0),
PRIMARY KEY (ancestor, descendant),
CHECK ((ancestor = descendant AND distance = 0)
OR (ancestor <> descendant AND distance > 0))
) WITHOUT ROWID;
CREATE INDEX closure_reverse
ON closure(descendant, distance, ancestor);
""")
return db
@contextmanager
def atomic(db):
db.execute("BEGIN IMMEDIATE")
try:
yield
db.execute("COMMIT")
except BaseException:
if db.in_transaction:
db.execute("ROLLBACK")
raise
def add_leaf(db, node_id, name, parent_id):
# Call only inside the caller's transaction.
assert db.in_transaction
if parent_id is not None and not db.execute(
"SELECT 1 FROM node WHERE id = ?", (parent_id,)
).fetchone():
raise ValueError("parent not found")
db.execute("INSERT INTO node VALUES (?, ?, ?)",
(node_id, name, parent_id))
db.execute("INSERT INTO closure VALUES (?, ?, 0)", (node_id, node_id))
if parent_id is not None:
db.execute("""
INSERT INTO closure(ancestor, descendant, distance)
SELECT ancestor, ?, distance + 1
FROM closure WHERE descendant = ?
""", (node_id, parent_id))
def seed(db):
rows = [(1, "Root", None), (2, "Books", 1), (3, "Digital", 1),
(4, "Python", 2), (5, "Async", 4), (6, "Video", 3)]
with atomic(db):
for row in rows:
add_leaf(db, *row)
def expected_paths(db):
# node.parent_id is the authoritative structure for this application.
parents = dict(db.execute("SELECT id, parent_id FROM node"))
expected = set()
for descendant in parents:
ancestor, distance, seen = descendant, 0, set()
while ancestor is not None:
if ancestor not in parents:
raise ValueError("orphan parent")
if ancestor in seen:
raise ValueError("cycle in node")
seen.add(ancestor)
expected.add((ancestor, descendant, distance))
ancestor = parents[ancestor]
distance += 1
return expected
def audit(db):
expected = expected_paths(db)
actual = set(db.execute("SELECT * FROM closure"))
return sorted(expected - actual), sorted(actual - expected)
def rebuild(db):
with atomic(db):
expected = expected_paths(db)
db.execute("DELETE FROM closure")
db.executemany("INSERT INTO closure VALUES (?, ?, ?)", sorted(expected))
assert audit(db) == ([], [])
assert db.execute("PRAGMA foreign_key_check").fetchall() == []
return len(expected)
with closing(connect()) as db:
seed(db)
with atomic(db):
db.execute("DELETE FROM closure WHERE distance > 1")
repaired = rebuild(db)
assert repaired == 15
print("rebuilt rows:", repaired)
print("audit:", audit(db))
before = db.execute("SELECT * FROM closure ORDER BY 1, 2").fetchall()
# Foreign keys permit this cycle; the rebuild validator must reject it.
with atomic(db):
db.execute("UPDATE node SET parent_id = 5 WHERE id = 2")
try:
rebuild(db)
except ValueError as exc:
assert str(exc) == "cycle in node"
else:
raise AssertionError("cycle not detected")
assert db.execute("SELECT * FROM closure ORDER BY 1, 2").fetchall() == before
print("bad source rejected:", True)预期输出:
rebuilt rows: 15 audit: ([], []) bad source rejected: True
最后一段故意先提交一个错误的父关系,用来证明重建会拒绝坏来源,且不会破坏现有闭包。它不会替先前事务撤销错误父关系,此时库仍然不一致,必须恢复正确的父关系后才能继续使用。把拒绝重建理解为已经修复,是另一个需要避免的误区。
闭包表最适合祖先、子树和继承范围读取频繁,而层级调整相对受控的业务。若结构很深、经常整棵搬迁,或者允许一个节点有多个父节点,当前模型的空间成本、写入成本和距离定义都要重新评估。多父图可能有多条不同长度路径,本文的单一距离主键与移动算法不再直接适用。
落地前的核对清单
先确定只支持单父树或森林,并明确节点表是结构事实来源;再把所有写入口收敛到统一事务,禁止绕过维护函数修改父关系。迁移时检查自身零距离记录、直接父边距离一、全部路径的完整性与准确距离。移动测试覆盖共同祖先距离变化、同父无操作、非法目标和中途故障;删除前确认业务引用策略。上线之后保留可重复运行的审计和重建流程,任何读优化都不能以失去可验证性为代价。
闭包表并不是把递归换一种写法,而是把计算的时间从读取时挪到结构变更时。理解这一点,就能同时看见它的优势和代价:读查询直观,路径距离现成,但每次移动都承担维护物化事实的责任。只有将距离不变量、事务边界和修复入口一起设计,分类检索与继承范围查询才会真正可靠。
本文 SQL 与算法为独立示例实现。官方参考:Python sqlite3、SQLite 表约束、SQLite 事务、SQLite 外键。资料核验日期:2026 年 10 月 18 日。

