Python sqlite3 物化路径树:安全移动子树与原子回滚

10-19 5阅读

把一棵栏目树装进 SQLite,难点往往不在第一次查询,而在用户拖动一个目录的那一刻。目录下面可能还有几十个子目录,如果只改当前位置,后代保存的祖先地址就会留在旧地方。物化路径把从根到自己的完整路线存进每一行,读取子树很直接,代价则是移动时必须把整段分支一起改写。本文只围绕这份路径表示及其原子更新展开,不把递归邻接查询或闭包表重新讲一遍。

我们的数据模型是一片森林:允许多个根,每个节点最多一个直接父节点,节点编号在表内全局唯一且保持不变。业务名称可以随时修改,但绝不进入路径。示例同时保存 parent_id,用来快速找直接父节点和核对冗余信息;path 是祖先链的物化结果,不是另一条可以随便修改的事实。移动的本质是换掉整棵子树的共同前缀,同时只改变被移动子树根节点的直接父指针。

下面九组代码都能单独保存运行,只依赖标准库,不需要前一组留下数据库或变量。建议使用 Python 3.11 或更新版本,并以 python -X dev -W error example.py 执行。本文在 Python 3.12.14、SQLite 3.53.1 上逐组核对输出。所有连接都明确关闭;需要自己控制事务的示例显式选择隔离配置,不依赖未来可能变化的默认行为。相关连接参数与资源管理规则见 Python sqlite3 官方文档。

Python sqlite3 物化路径树:安全移动子树与原子回滚
模型生成的概念插图:移动的是保持内部连接的一整段分支,透明容器象征提交或回滚的事务边界,并非实际数据库执行流程图。

一、先把路径编码的规则钉死

本文选用 /1/2/17/ 这种首尾都有斜杠的编码。每个片段只能是无前导零的 ASCII 十进制正整数,上限取 SQLite 有符号六十四位整数范围;根的深度为零。拒绝布尔值很重要,因为 Python 中 bool 是 int 的子类,直接用 isinstance 可能把 True 当成编号一。统一编码让同一个节点链只有一种写法,避免 /02/ 与 /2/ 在字符串层面成为两个地址。

这里不接收业务方拼好的任意路径。接口接受节点编号,应用自己生成地址。反向解析用于检查历史数据和测试,除了分隔符与数字,还拒绝重复编号以及过长片段。重复编号不等同于完整图验证,但在一条祖先链上已经足以说明状态不可信。这样的窄字符集也为后面的通配符查询提供了可证明的安全边界。

import re

MAX_ID = 2**63 - 1

def encode(ids):
    ids = tuple(ids)
    if not ids:
        raise ValueError("empty path")
    for value in ids:
        if type(value) is not int or not 1 <= value <= MAX_ID:
            raise ValueError("invalid ID")
    if len(ids) != len(set(ids)):
        raise ValueError("repeated ID")
    return "/" + "/".join(map(str, ids)) + "/"

def decode(path):
    if not isinstance(path, str) or not re.fullmatch(
        r"/(?:[1-9][0-9]*/)+", path
    ):
        raise ValueError("invalid path")
    parts = path[1:-1].split("/")
    if any(len(part) > 19 for part in parts):
        raise ValueError("oversized ID")
    ids = tuple(map(int, parts))
    if encode(ids) != path:
        raise ValueError("noncanonical path")
    return ids

print(encode([1, 2, 17]))
print(decode("/1/2/17/"))
rejected = 0
for value in ["/1/02/", "/1//2/", "/1/2", "/1/1/", "/1/2/"]:
    try:
        decode(value)
    except ValueError:
        rejected += 1
for value in [True, 0, -1, "2", 2**63]:
    try:
        encode([1, value])
    except ValueError:
        rejected += 1
print("rejected:", rejected)

运行结果:

/1/2/17/
(1, 2, 17)
rejected: 10

二、表约束守住底线,插入负责维护祖先链

表里存编号、直接父编号、路径和深度。UNIQUE(path) 防止两行占据同一条完整路径;它不代表父节点只能有一个孩子。一个节点的唯一父关系来自单行 parent_id 字段,不能把 parent_id 设成唯一索引,否则普通分叉也无法表示。下面的插入函数从父行读取路径后追加当前编号,而不是让调用者传入 path 或 depth。

外键必须对每个连接启用,而且应该在事务外设置。它只证明被引用的父编号存在,不会检查路径前缀、发现任意长的环,或自动修正深度,这一点可对照 SQLite 外键说明。示例从空库开始,只有 add 写入,所以父路径可信。若数据库还有旧导入脚本或其他写入入口,就要使用后文的完整审计,不能把几条 CHECK 当成整个树模型的证明。

import sqlite3
from contextlib import closing

options = {"isolation_level": None}
if hasattr(sqlite3, "LEGACY_TRANSACTION_CONTROL"):
    options["autocommit"] = sqlite3.LEGACY_TRANSACTION_CONTROL
with closing(sqlite3.connect(":memory:", **options)) as db:
    db.execute("PRAGMA foreign_keys = ON")
    db.execute("""
        CREATE TABLE nodes (
            id INTEGER PRIMARY KEY CHECK (id > 0),
            parent_id INTEGER REFERENCES nodes(id),
            path TEXT NOT NULL COLLATE BINARY UNIQUE,
            depth INTEGER NOT NULL CHECK (
                typeof(depth) = 'integer' AND depth BETWEEN 0 AND 8
            ),
            CHECK (parent_id IS NULL OR parent_id <> id)
        )
    """)
    def add(node_id, parent_id=None):
        if type(node_id) is not int or not 1 <= node_id <= 2**63 - 1:
            raise ValueError("invalid ID")
        if parent_id is not None and (
            type(parent_id) is not int or not 1 <= parent_id <= 2**63 - 1
        ):
            raise ValueError("invalid parent ID")
        if db.in_transaction:
            raise ValueError("add owns its transaction")
        db.execute("BEGIN IMMEDIATE")
        try:
            path, depth = f"/{node_id}/", 0
            if parent_id is not None:
                parent = db.execute(
                    "SELECT path, depth FROM nodes WHERE id = ?", (parent_id,)
                ).fetchone()
                if parent is None:
                    raise ValueError("missing parent")
                path, depth = parent[0] + f"{node_id}/", parent[1] + 1
            if depth > 8:
                raise ValueError("too deep")
            db.execute("INSERT INTO nodes VALUES (?, ?, ?, ?)",
                       (node_id, parent_id, path, depth))
            db.execute("COMMIT")
        except BaseException:
            if db.in_transaction:
                db.execute("ROLLBACK")
            raise
    add(1)
    add(2, 1)
    add(4, 2)
    print(db.execute("SELECT * FROM nodes ORDER BY id").fetchall())
    print("foreign keys:", db.execute("PRAGMA foreign_keys").fetchone()[0])

运行结果:

[(1, None, '/1/', 0), (2, 1, '/1/2/', 1), (4, 2, '/1/2/4/', 2)]
foreign keys: 1

三、查询后代时,末尾分隔符不能省

最常见的误判是拿 /1/2 直接做前缀匹配,这会把 /1/20/ 也看成节点二的后代。正确查询使用已经规范化、末尾带斜杠的完整前缀。子树通常包含当前节点;严格后代则额外排除当前路径。接口要明确这两种语义,否则统计数量、批量删除和移动预览很容易差一行。

这里使用 GLOB,只有程序追加的星号才是通配符,已验证路径里没有星号、问号或方括号。参数绑定解决 SQL 值传递,不能替任意业务字符串取消通配符含义;允许自由文本路径时必须另行设计编码。其匹配规则见 SQLite 表达式文档。同例还演示 BINARY 排序下的半开区间:把最后一个斜杠替换为 ASCII 中紧随其后的零,得到前缀上界。这一技巧仅适用于这里的字符集和排序规则。

import sqlite3
from contextlib import closing

with closing(sqlite3.connect(":memory:")) as db:
    db.execute("CREATE TABLE nodes(id INTEGER PRIMARY KEY, path TEXT COLLATE BINARY)")
    db.execute("CREATE INDEX path_index ON nodes(path)")
    db.executemany("INSERT INTO nodes VALUES (?, ?)", [
        (1, "/1/"), (2, "/1/2/"), (4, "/1/2/4/"),
        (20, "/1/20/"), (21, "/1/21/"),
    ])
    prefix = db.execute("SELECT path FROM nodes WHERE id = ?", (2,)).fetchone()[0]
    wrong = db.execute(
        "SELECT id FROM nodes WHERE path GLOB ? ORDER BY id",
        (prefix.rstrip("/") + "*",),
    ).fetchall()
    correct = db.execute(
        "SELECT id FROM nodes WHERE path GLOB ? ORDER BY id", (prefix + "*",)
    ).fetchall()
    descendants = db.execute(
        "SELECT id FROM nodes WHERE path GLOB ? AND path <> ? ORDER BY id",
        (prefix + "*", prefix),
    ).fetchall()
    upper = prefix[:-1] + "0"
    ranged = db.execute(
        "SELECT id FROM nodes WHERE path >= ? AND path < ? ORDER BY id",
        (prefix, upper),
    ).fetchall()
    assert ranged == correct
    print("missing separator:", wrong)
    print("subtree:", correct)
    print("strict descendants:", descendants)
    print("range agrees:", ranged == correct)

运行结果:

missing separator: [(2,), (4,), (20,), (21,)]
subtree: [(2,), (4,)]
strict descendants: [(4,)]
range agrees: True

四、面包屑来自路径顺序,不来自查询返回顺序

路径已经保存了祖先编号,因此展示面包屑时可以一次取出这些编号对应的名称,再按原路径顺序组装。SQL 的 IN 条件不承诺按参数顺序返回,不能把 fetchall 的顺序直接当成祖先顺序。下面只动态生成占位符个数,编号仍然作为绑定参数传入;不把节点编号串进 SQL 字面量。

读路径和读名称是两个查询,本例的内存数据库没有并发写入。实际页面若要求同一时刻的严格一致视图,应把两次读取放在同一个显式读事务中,或者让单条查询返回所需结果。若允许名称稍有滞后,也要明确这是展示策略。编号稳定、名称独立的好处在这里很明显:重命名目录无需改写全部后代的路径。

import re
import sqlite3
from contextlib import closing

with closing(sqlite3.connect(":memory:")) as db:
    db.execute("CREATE TABLE nodes(id INTEGER PRIMARY KEY, name TEXT, path TEXT)")
    db.executemany("INSERT INTO nodes VALUES (?, ?, ?)", [
        (1, "知识库", "/1/"), (2, "数据库", "/1/2/"),
        (17, "事务", "/1/2/17/"),
    ])
    path = db.execute("SELECT path FROM nodes WHERE id = ?", (17,)).fetchone()[0]
    if not re.fullmatch(r"/(?:[1-9][0-9]*/)+", path):
        raise ValueError("bad path")
    ids = tuple(map(int, path[1:-1].split("/")))
    if len(ids) != len(set(ids)):
        raise ValueError("cycle in path")
    marks = ",".join("?" for _ in ids)
    names = dict(db.execute(
        f"SELECT id, name FROM nodes WHERE id IN ({marks})", ids
    ).fetchall())
    if set(names) != set(ids):
        raise ValueError("missing ancestor")
    print(" / ".join(names[node_id] for node_id in ids))
    print("ancestor IDs:", ids[:-1])
    print("depth:", len(ids) - 1)

运行结果:

知识库 / 数据库 / 事务
ancestor IDs: (1, 2)
depth: 2

五、移动前先算新前缀与整棵子树的深度差

移动节点二到节点三下面,新前缀从 /1/2/ 变成 /1/3/2/。原来路径中不属于旧前缀的后缀保持不动,因此原来的内部父子关系也保持不动。深度变化是一个固定差值,对所有子树成员相同。不过检查目标深度时,必须看最深后代加上差值,而不能只看被移动节点本身是否超过限制。

防环检查也不需要递归:在可信的规范路径里,如果目标父路径以源路径开头,目标就是源节点自身或其后代,必须拒绝。根迁移用 None 表示,新的路径只剩当前编号。下面先把数学关系单独拿出来验证,它不是可以脱离锁使用的最终服务接口;正式移动必须在拿到写事务后重新读取这些数据。

def plan_move(source, destination, subtree_max_depth, max_depth):
    # Inputs are canonical rows read from an already-validated tree.
    node_id, old_path, old_depth = source
    if destination is None:
        new_path, new_depth = f"/{node_id}/", 0
    else:
        parent_path, parent_depth = destination
        if parent_path.startswith(old_path):
            raise ValueError("cycle")
        new_path = parent_path + f"{node_id}/"
        new_depth = parent_depth + 1
    delta = new_depth - old_depth
    if subtree_max_depth + delta > max_depth:
        raise ValueError("depth")
    return new_path, delta

source = (2, "/1/2/", 1)
print("plan:", plan_move(source, ("/1/3/", 1), 3, 4))
for label, destination, limit in [
    ("self", ("/1/2/", 1), 8),
    ("descendant", ("/1/2/4/", 2), 8),
    ("deepest leaf", ("/1/3/", 1), 3),
]:
    try:
        plan_move(source, destination, 3, limit)
    except ValueError as exc:
        print(label + ":", str(exc))
print("to root:", plan_move(source, None, 3, 8))

运行结果:

plan: ('/1/3/2/', 1)
self: cycle
descendant: cycle
deepest leaf: depth
to root: ('/2/', -1)

六、完整移动:先锁定写事务,再用一条 UPDATE 换前缀

完整实现先拒绝外层已有事务,再执行 BEGIN IMMEDIATE,然后读取并审计树。先开始写事务,避免在校验结束到真正更新之间被另一个写入者改变目标。SQLite 同时只能有一个写事务,IMMEDIATE 也可能因为已有写入者而失败,详见 事务官方说明。这不是拿到锁后可以无限停留的理由,所有网络调用和用户交互都应放在事务之外。

UPDATE 用新前缀拼接旧路径剩余部分。SQLite 的 substr 起点从一开始,所以应传 len(old_path) + 1,相关定义见 内置字符串函数说明。CASE 表达式只为源节点改 parent_id;如果把整棵子树的父编号都改成目标,路径看起来可能还像树,真实结构却已经被压扁。后代的深度和平移后的路径要一起更新,不能拆成几个自动提交的语句。

为了让教学实现具备可验证的前提,audit 在更新前后核对全部节点:最后一个路径片段必须等于自身编号,片段数对应深度,根路径必须只有自己,非根路径必须精确等于父路径加自身编号。这会增加全表扫描,不能宣传为只与子树大小有关的高性能方案。全局唯一编号和这些不变量保证合法移动不会与外部现有路径撞位;数据库的唯一约束仍然保留为最后一道防线。

import re
import sqlite3
from contextlib import closing

MAX_ID = 2**63 - 1
MAX_DEPTH = 8
SCHEMA = """
CREATE TABLE nodes (
    id INTEGER PRIMARY KEY CHECK (id > 0),
    parent_id INTEGER REFERENCES nodes(id),
    path TEXT NOT NULL COLLATE BINARY UNIQUE,
    depth INTEGER NOT NULL CHECK (
        typeof(depth) = 'integer' AND depth BETWEEN 0 AND 8
    ),
    CHECK (typeof(path) = 'text'),
    CHECK (parent_id IS NULL OR parent_id <> id)
)
"""
SEED = [
    (1, None, "/1/", 0),
    (2, 1, "/1/2/", 1),
    (3, 1, "/1/3/", 1),
    (4, 2, "/1/2/4/", 2),
    (5, 4, "/1/2/4/5/", 3),
    (12, 1, "/1/12/", 1),
]

def connect(factory=sqlite3.Connection):
    options = {"isolation_level": None, "factory": factory}
    if hasattr(sqlite3, "LEGACY_TRANSACTION_CONTROL"):
        options["autocommit"] = sqlite3.LEGACY_TRANSACTION_CONTROL
    db = sqlite3.connect(":memory:", **options)
    db.execute("PRAGMA foreign_keys = ON")
    return db

def require_id(value):
    if type(value) is not int or not 1 <= value <= MAX_ID:
        raise ValueError("ID must be a positive signed-64-bit integer")

def decode(path):
    if not isinstance(path, str) or not re.fullmatch(
        r"/(?:[1-9][0-9]*/)+", path
    ):
        raise ValueError("noncanonical path")
    parts = path[1:-1].split("/")
    if any(len(part) > 19 for part in parts):
        raise ValueError("ID too long")
    ids = tuple(map(int, parts))
    for value in ids:
        require_id(value)
    if len(ids) != len(set(ids)):
        raise ValueError("repeated ID")
    return ids

def audit(db):
    rows = db.execute(
        "SELECT id, parent_id, path, depth FROM nodes"
    ).fetchall()
    by_id = {row[0]: row for row in rows}
    for node_id, parent_id, path, depth in rows:
        ids = decode(path)
        if ids[-1] != node_id or depth != len(ids) - 1:
            raise ValueError("path, ID and depth disagree")
        if not 0 <= depth <= MAX_DEPTH:
            raise ValueError("invalid depth")
        if parent_id is None:
            expected = f"/{node_id}/"
        else:
            if parent_id not in by_id:
                raise ValueError("missing parent")
            expected = by_id[parent_id][2] + f"{node_id}/"
        if path != expected:
            raise ValueError("parent and path disagree")
    return by_id

def seed(db):
    db.execute(SCHEMA)
    db.executemany("INSERT INTO nodes VALUES (?, ?, ?, ?)", SEED)
    audit(db)

def move_subtree(db, node_id, new_parent_id, *, max_depth=MAX_DEPTH):
    require_id(node_id)
    if new_parent_id is not None:
        require_id(new_parent_id)
    if type(max_depth) is not int or not 0 <= max_depth <= MAX_DEPTH:
        raise ValueError("invalid depth limit")
    if db.in_transaction:
        raise ValueError("move owns its transaction")
    db.execute("BEGIN IMMEDIATE")
    try:
        rows = audit(db)
        if node_id not in rows:
            raise ValueError("source missing")
        old_path, old_depth = rows[node_id][2:]
        if new_parent_id is None:
            new_path, new_depth = f"/{node_id}/", 0
        else:
            if new_parent_id not in rows:
                raise ValueError("destination missing")
            parent_path, parent_depth = rows[new_parent_id][2:]
            if parent_path.startswith(old_path):
                raise ValueError("self or descendant destination")
            new_path = parent_path + f"{node_id}/"
            new_depth = parent_depth + 1
        delta = new_depth - old_depth
        count, deepest = db.execute(
            "SELECT count(*), max(depth) FROM nodes WHERE path GLOB ?",
            (old_path + "*",),
        ).fetchone()
        if deepest + delta > max_depth:
            raise ValueError("subtree would exceed depth limit")
        if new_path == old_path:
            db.execute("COMMIT")
            return 0
        changed = db.execute("""
            UPDATE nodes
            SET path = ? || substr(path, ?),
                depth = depth + ?,
                parent_id = CASE WHEN id = ? THEN ? ELSE parent_id END
            WHERE path GLOB ?
        """, (
            new_path, len(old_path) + 1, delta,
            node_id, new_parent_id, old_path + "*",
        )).rowcount
        if changed != count:
            raise RuntimeError("unexpected affected-row count")
        audit(db)
        db.execute("COMMIT")
        return changed
    except BaseException:
        if db.in_transaction:
            db.execute("ROLLBACK")
        raise

with closing(connect()) as db:
    seed(db)
    print("affected:", move_subtree(db, 2, 3, max_depth=4))
    for row in db.execute("SELECT * FROM nodes WHERE id IN (2, 4, 5) ORDER BY id"):
        print(row)
    print("same parent:", move_subtree(db, 2, 3))
    print("to root:", move_subtree(db, 2, None))
    print(db.execute("SELECT * FROM nodes WHERE id = 2").fetchone())

运行结果:

affected: 3
(2, 3, '/1/3/2/', 2)
(4, 2, '/1/3/2/4/', 3)
(5, 4, '/1/3/2/4/5/', 4)
same parent: 0
to root: 3
(2, None, '/2/', 0)

七、回滚测试要发生在写入之后

仅测试非法目标提前报错,并不能证明已经写入的数据会被恢复。本例通过连接子类在 COMMIT 送达 SQLite 之前故意抛异常,确保 UPDATE 已执行、提交尚未发生,然后比较所有行。测试的是应用异常路径上的原子回滚,不是模拟断电、磁盘损坏或操作系统崩溃。后面四次拒绝操作还分别覆盖自己、后代、最深叶子超限以及目标不存在。

函数在异常处理里检查 in_transaction,仍有事务才执行 ROLLBACK,之后把原异常交还调用者;它没有用异常吞掉失败并返回成功。测试最后重新执行合法移动,验证失败后的连接仍可正常使用。生产环境应保留数据库默认安全日志机制或合理配置 WAL,不能关闭回滚日志后继续沿用这里的保证。对于提交状态不明的进程中断,需要重新读取业务状态或设计操作编号,不能凭调用超时认定更新一定失败。

import re
import sqlite3
from contextlib import closing

MAX_ID = 2**63 - 1
MAX_DEPTH = 8
SCHEMA = """
CREATE TABLE nodes (
    id INTEGER PRIMARY KEY CHECK (id > 0),
    parent_id INTEGER REFERENCES nodes(id),
    path TEXT NOT NULL COLLATE BINARY UNIQUE,
    depth INTEGER NOT NULL CHECK (
        typeof(depth) = 'integer' AND depth BETWEEN 0 AND 8
    ),
    CHECK (typeof(path) = 'text'),
    CHECK (parent_id IS NULL OR parent_id <> id)
)
"""
SEED = [
    (1, None, "/1/", 0),
    (2, 1, "/1/2/", 1),
    (3, 1, "/1/3/", 1),
    (4, 2, "/1/2/4/", 2),
    (5, 4, "/1/2/4/5/", 3),
    (12, 1, "/1/12/", 1),
]

def connect(factory=sqlite3.Connection):
    options = {"isolation_level": None, "factory": factory}
    if hasattr(sqlite3, "LEGACY_TRANSACTION_CONTROL"):
        options["autocommit"] = sqlite3.LEGACY_TRANSACTION_CONTROL
    db = sqlite3.connect(":memory:", **options)
    db.execute("PRAGMA foreign_keys = ON")
    return db

def require_id(value):
    if type(value) is not int or not 1 <= value <= MAX_ID:
        raise ValueError("ID must be a positive signed-64-bit integer")

def decode(path):
    if not isinstance(path, str) or not re.fullmatch(
        r"/(?:[1-9][0-9]*/)+", path
    ):
        raise ValueError("noncanonical path")
    parts = path[1:-1].split("/")
    if any(len(part) > 19 for part in parts):
        raise ValueError("ID too long")
    ids = tuple(map(int, parts))
    for value in ids:
        require_id(value)
    if len(ids) != len(set(ids)):
        raise ValueError("repeated ID")
    return ids

def audit(db):
    rows = db.execute(
        "SELECT id, parent_id, path, depth FROM nodes"
    ).fetchall()
    by_id = {row[0]: row for row in rows}
    for node_id, parent_id, path, depth in rows:
        ids = decode(path)
        if ids[-1] != node_id or depth != len(ids) - 1:
            raise ValueError("path, ID and depth disagree")
        if not 0 <= depth <= MAX_DEPTH:
            raise ValueError("invalid depth")
        if parent_id is None:
            expected = f"/{node_id}/"
        else:
            if parent_id not in by_id:
                raise ValueError("missing parent")
            expected = by_id[parent_id][2] + f"{node_id}/"
        if path != expected:
            raise ValueError("parent and path disagree")
    return by_id

def seed(db):
    db.execute(SCHEMA)
    db.executemany("INSERT INTO nodes VALUES (?, ?, ?, ?)", SEED)
    audit(db)

def move_subtree(db, node_id, new_parent_id, *, max_depth=MAX_DEPTH):
    require_id(node_id)
    if new_parent_id is not None:
        require_id(new_parent_id)
    if type(max_depth) is not int or not 0 <= max_depth <= MAX_DEPTH:
        raise ValueError("invalid depth limit")
    if db.in_transaction:
        raise ValueError("move owns its transaction")
    db.execute("BEGIN IMMEDIATE")
    try:
        rows = audit(db)
        if node_id not in rows:
            raise ValueError("source missing")
        old_path, old_depth = rows[node_id][2:]
        if new_parent_id is None:
            new_path, new_depth = f"/{node_id}/", 0
        else:
            if new_parent_id not in rows:
                raise ValueError("destination missing")
            parent_path, parent_depth = rows[new_parent_id][2:]
            if parent_path.startswith(old_path):
                raise ValueError("self or descendant destination")
            new_path = parent_path + f"{node_id}/"
            new_depth = parent_depth + 1
        delta = new_depth - old_depth
        count, deepest = db.execute(
            "SELECT count(*), max(depth) FROM nodes WHERE path GLOB ?",
            (old_path + "*",),
        ).fetchone()
        if deepest + delta > max_depth:
            raise ValueError("subtree would exceed depth limit")
        if new_path == old_path:
            db.execute("COMMIT")
            return 0
        changed = db.execute("""
            UPDATE nodes
            SET path = ? || substr(path, ?),
                depth = depth + ?,
                parent_id = CASE WHEN id = ? THEN ? ELSE parent_id END
            WHERE path GLOB ?
        """, (
            new_path, len(old_path) + 1, delta,
            node_id, new_parent_id, old_path + "*",
        )).rowcount
        if changed != count:
            raise RuntimeError("unexpected affected-row count")
        audit(db)
        db.execute("COMMIT")
        return changed
    except BaseException:
        if db.in_transaction:
            db.execute("ROLLBACK")
        raise

class CommitFailure(sqlite3.Connection):
    fail_commit = False

    def execute(self, sql, parameters=()):
        if sql == "COMMIT" and self.fail_commit:
            self.fail_commit = False
            raise sqlite3.OperationalError("simulated before COMMIT")
        return super().execute(sql, parameters)

with closing(connect(factory=CommitFailure)) as db:
    seed(db)
    before = db.execute("SELECT * FROM nodes ORDER BY id").fetchall()
    db.fail_commit = True
    try:
        move_subtree(db, 2, 3)
    except sqlite3.OperationalError as exc:
        print(str(exc))
    after = db.execute("SELECT * FROM nodes ORDER BY id").fetchall()
    print("full rollback:", before == after)
    print("transaction open:", db.in_transaction)
    for parent, limit in [(2, 8), (5, 8), (3, 3), (999, 8)]:
        try:
            move_subtree(db, 2, parent, max_depth=limit)
        except ValueError:
            assert db.execute("SELECT * FROM nodes ORDER BY id").fetchall() == before
    print("four rejected moves preserved all rows")
    print("retry affected:", move_subtree(db, 2, 3))

运行结果:

simulated before COMMIT
full rollback: True
transaction open: False
four rejected moves preserved all rows
retry affected: 3

八、并发冲突时,重试整次决策,不重放旧路径

内存库不足以演示两个独立连接争用同一个数据库,因此这一组使用临时文件。第一个连接持有写事务时,第二个连接以零等待尝试进入,应该收到 SQLITE_BUSY;释放第一个事务后再重新进入并读取当前值。零等待只是为了使测试迅速、确定,真实服务应采用有限等待或带上限的退避策略。

如果一次移动遭遇锁竞争,重试单位是重新开启事务、重新读取源和目标、重新检查环与深度、重新改写并提交。不能拿第一次在锁外算出的前缀直接更新。也不要把所有 OperationalError 都当成锁忙无限重试,磁盘满、SQL 拼写错误与数据库损坏需要不同处理。这里没有跨进程业务幂等性承诺,重复请求的结果仍要由接口契约明确,例如移动到现有父节点返回零。

import sqlite3
from contextlib import closing
from pathlib import Path
from tempfile import TemporaryDirectory

options = {"isolation_level": None, "timeout": 0.0}
if hasattr(sqlite3, "LEGACY_TRANSACTION_CONTROL"):
    options["autocommit"] = sqlite3.LEGACY_TRANSACTION_CONTROL
with TemporaryDirectory() as folder:
    path = Path(folder) / "tree.db"
    with closing(sqlite3.connect(path, **options)) as first, closing(
        sqlite3.connect(path, **options)
    ) as second:
        first.execute("CREATE TABLE state(value INTEGER)")
        first.execute("INSERT INTO state VALUES (1)")
        first.execute("BEGIN IMMEDIATE")
        try:
            second.execute("BEGIN IMMEDIATE")
        except sqlite3.OperationalError as exc:
            if exc.sqlite_errorcode != sqlite3.SQLITE_BUSY:
                raise
            print("second writer: busy")
        else:
            second.execute("ROLLBACK")
            raise AssertionError("second writer unexpectedly acquired lock")
        finally:
            first.execute("ROLLBACK")
        second.execute("BEGIN IMMEDIATE")
        try:
            value = second.execute("SELECT value FROM state").fetchone()[0]
            second.execute("UPDATE state SET value = ?", (value + 1,))
            second.execute("COMMIT")
        except BaseException:
            if second.in_transaction:
                second.execute("ROLLBACK")
            raise
        print("retry value:", first.execute("SELECT value FROM state").fetchone()[0])

运行结果:

second writer: busy
retry value: 2

九、用另一种表示验证移动结果

最后一组用 parent_id 字典构造一个小型参考模型,再根据父指针重新生成全部路径。参考模型不复用前缀替换算法,所以能发现更有价值的偏差。固定随机种子依次尝试两百次移动,包括跨根移动、移为根以及无效成环操作。合法操作逐行比较父编号、路径和深度;非法操作则要求数据库完全不变,并在每一步检查事务已经结束。

这种小规模性质测试不能替代真实文件系统上的耐久性测试、海量数据压测或多进程竞争测试,但比只看一次成功输出更接近核心契约。上线前还应加入深链达到最大边界、编号相近却不是后代、损坏路径拒绝、重复请求、写锁超时和授权失败等样本。尤其应验证所有能修改 id、parent_id、path、depth 的入口都经过同一套约束,绕开入口的脚本足以破坏应用层证明。

import re
import sqlite3
from contextlib import closing

MAX_ID = 2**63 - 1
MAX_DEPTH = 8
SCHEMA = """
CREATE TABLE nodes (
    id INTEGER PRIMARY KEY CHECK (id > 0),
    parent_id INTEGER REFERENCES nodes(id),
    path TEXT NOT NULL COLLATE BINARY UNIQUE,
    depth INTEGER NOT NULL CHECK (
        typeof(depth) = 'integer' AND depth BETWEEN 0 AND 8
    ),
    CHECK (typeof(path) = 'text'),
    CHECK (parent_id IS NULL OR parent_id <> id)
)
"""
SEED = [
    (1, None, "/1/", 0),
    (2, 1, "/1/2/", 1),
    (3, 1, "/1/3/", 1),
    (4, 2, "/1/2/4/", 2),
    (5, 4, "/1/2/4/5/", 3),
    (12, 1, "/1/12/", 1),
]

def connect(factory=sqlite3.Connection):
    options = {"isolation_level": None, "factory": factory}
    if hasattr(sqlite3, "LEGACY_TRANSACTION_CONTROL"):
        options["autocommit"] = sqlite3.LEGACY_TRANSACTION_CONTROL
    db = sqlite3.connect(":memory:", **options)
    db.execute("PRAGMA foreign_keys = ON")
    return db

def require_id(value):
    if type(value) is not int or not 1 <= value <= MAX_ID:
        raise ValueError("ID must be a positive signed-64-bit integer")

def decode(path):
    if not isinstance(path, str) or not re.fullmatch(
        r"/(?:[1-9][0-9]*/)+", path
    ):
        raise ValueError("noncanonical path")
    parts = path[1:-1].split("/")
    if any(len(part) > 19 for part in parts):
        raise ValueError("ID too long")
    ids = tuple(map(int, parts))
    for value in ids:
        require_id(value)
    if len(ids) != len(set(ids)):
        raise ValueError("repeated ID")
    return ids

def audit(db):
    rows = db.execute(
        "SELECT id, parent_id, path, depth FROM nodes"
    ).fetchall()
    by_id = {row[0]: row for row in rows}
    for node_id, parent_id, path, depth in rows:
        ids = decode(path)
        if ids[-1] != node_id or depth != len(ids) - 1:
            raise ValueError("path, ID and depth disagree")
        if not 0 <= depth <= MAX_DEPTH:
            raise ValueError("invalid depth")
        if parent_id is None:
            expected = f"/{node_id}/"
        else:
            if parent_id not in by_id:
                raise ValueError("missing parent")
            expected = by_id[parent_id][2] + f"{node_id}/"
        if path != expected:
            raise ValueError("parent and path disagree")
    return by_id

def seed(db):
    db.execute(SCHEMA)
    db.executemany("INSERT INTO nodes VALUES (?, ?, ?, ?)", SEED)
    audit(db)

def move_subtree(db, node_id, new_parent_id, *, max_depth=MAX_DEPTH):
    require_id(node_id)
    if new_parent_id is not None:
        require_id(new_parent_id)
    if type(max_depth) is not int or not 0 <= max_depth <= MAX_DEPTH:
        raise ValueError("invalid depth limit")
    if db.in_transaction:
        raise ValueError("move owns its transaction")
    db.execute("BEGIN IMMEDIATE")
    try:
        rows = audit(db)
        if node_id not in rows:
            raise ValueError("source missing")
        old_path, old_depth = rows[node_id][2:]
        if new_parent_id is None:
            new_path, new_depth = f"/{node_id}/", 0
        else:
            if new_parent_id not in rows:
                raise ValueError("destination missing")
            parent_path, parent_depth = rows[new_parent_id][2:]
            if parent_path.startswith(old_path):
                raise ValueError("self or descendant destination")
            new_path = parent_path + f"{node_id}/"
            new_depth = parent_depth + 1
        delta = new_depth - old_depth
        count, deepest = db.execute(
            "SELECT count(*), max(depth) FROM nodes WHERE path GLOB ?",
            (old_path + "*",),
        ).fetchone()
        if deepest + delta > max_depth:
            raise ValueError("subtree would exceed depth limit")
        if new_path == old_path:
            db.execute("COMMIT")
            return 0
        changed = db.execute("""
            UPDATE nodes
            SET path = ? || substr(path, ?),
                depth = depth + ?,
                parent_id = CASE WHEN id = ? THEN ? ELSE parent_id END
            WHERE path GLOB ?
        """, (
            new_path, len(old_path) + 1, delta,
            node_id, new_parent_id, old_path + "*",
        )).rowcount
        if changed != count:
            raise RuntimeError("unexpected affected-row count")
        audit(db)
        db.execute("COMMIT")
        return changed
    except BaseException:
        if db.in_transaction:
            db.execute("ROLLBACK")
        raise

import random

def expected_paths(parents):
    result = {}
    for node_id in parents:
        chain, seen, current = [], set(), node_id
        while current is not None:
            if current in seen:
                raise ValueError("cycle")
            seen.add(current)
            chain.append(current)
            current = parents[current]
        chain.reverse()
        if len(chain) - 1 > MAX_DEPTH:
            raise ValueError("depth")
        result[node_id] = ("/" + "/".join(map(str, chain)) + "/", len(chain) - 1)
    return result

with closing(connect()) as db:
    seed(db)
    parents = {row[0]: row[1] for row in SEED}
    rng = random.Random(42)
    ids = sorted(parents)
    for _ in range(200):
        node_id = rng.choice(ids)
        destination = rng.choice([None] + ids)
        candidate = dict(parents)
        candidate[node_id] = destination
        before = db.execute("SELECT * FROM nodes ORDER BY id").fetchall()
        try:
            expected = expected_paths(candidate)
        except ValueError:
            try:
                move_subtree(db, node_id, destination)
            except ValueError:
                assert db.execute("SELECT * FROM nodes ORDER BY id").fetchall() == before
            else:
                raise AssertionError("invalid move accepted")
        else:
            move_subtree(db, node_id, destination)
            parents = candidate
            actual = db.execute("SELECT * FROM nodes ORDER BY id").fetchall()
            assert actual == [
                (key, parents[key], expected[key][0], expected[key][1])
                for key in ids
            ]
        assert not db.in_transaction
    print("200 deterministic moves: passed")
    print("foreign-key violations:", len(db.execute("PRAGMA foreign_key_check").fetchall()))

运行结果:

200 deterministic moves: passed
foreign-key violations: 0

适用范围与上线取舍

物化路径适合层级相对稳定、经常整段读取、偶尔移动的分类树或知识库。它把祖先关系复制进路径,因此子树越大、路径越长,移动涉及的写入和索引维护也越多。本文的前后全表审计还让每次移动带上整树检查成本。可以在明确禁止旁路写入、数据已经通过迁移审计的前提下设计增量校验,但那是另一份需要证明的实现,不能直接删掉检查后声称安全性不变。

路径索引不等于所有查询都会自动高效。前缀 GLOB 的优化有前提,BINARY 索引与参数形式也需要和实际查询保持一致;用 EXPLAIN QUERY PLAN 检查部署版本的计划,再用真实规模测量。可参照 SQLite 前缀匹配优化条件。不要在已有索引之外不加判断地再建重复索引,也不要声称 ORDER BY path 就是数字编号顺序:文本中的 12 会排在 2 前面,业务排序应有单独的顺序字段。

本文允许森林、禁止多父节点,不解决权限继承、审计日志、软删除、跨数据库迁移或名称唯一性。如果业务要求同级名称唯一,应单独定义规则,并在同一事务中检查目标父节点下的冲突。如果上层已有事务,本函数会明确拒绝,而不是偷偷提交上层工作;需要组合事务时,应重新设计事务所有权或使用保存点,并重新审查锁和失败传播。最终要守住的契约只有一句:校验基于同一个受保护状态,整棵子树作为一个整体提交,失败后不存在半棵搬走的树。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。